在Java脚本中合并两个json对象? [英] Merging two json objects in Java script?

查看:441
本文介绍了在Java脚本中合并两个json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你有没有在javascript中合并两个js ??

Have u merged two jsons in javascript ??

问题:

a={id:123,name:john,status:success};
b={id:123,status:inprocess,transId:245};

输出json应该像

{id:123,name:john,status:success,transId:245};

a中的所有值都应覆盖b中的值,并且不常见的键/值应出现在输出json。

All the values from a should override the ones in b and also the uncommon key/values should appear in output json.

我尝试了一些递归选项,但是cudnt实现了输出。

I tried out some recursive options but cudnt acheive the output.

推荐答案

您的 a b 变量无效json。

your a and b variable are not valid json.

<script>
//change your a and b variable to this.
 a={id:123,name:'john',status:'success'}; 
 b={id:123,status:'inprocess',transId:245};
$(document).ready(function(){

  $.extend(a,b);

});
</script>

a 将具有类似的结构

{
    id: 123
    name: "john"
    status: "inprocess"
    transId: 245

}

我用过jquery api

I've used jquery api

没有jquery

   a={id:123,name:'john',status:'success'}; 
   b={id:123,status:'inprocess',transId:245};

  extend(a,b);

其中,扩展功能为:

 function extend(a, b){
    for(var key in b)
        if(b.hasOwnProperty(key))
            a[key] = b[key];
    return a;
 }

ref1 ref2 ref3

这篇关于在Java脚本中合并两个json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆