[英]Merging two json objects in Java script?
Have u merged two jsons in javascript ?? 您是否在javascript中合并了两个json?
Problem: 问题:
a={id:123,name:john,status:success};
b={id:123,status:inprocess,transId:245};
Output json should be like 输出json应该像
{id:123,name:john,status:success,transId:245};
All the values from a should override the ones in b and also the uncommon key/values should appear in output json. 来自a的所有值应覆盖b中的值,并且不常见的键/值也应出现在输出json中。
I tried out some recursive options but cudnt acheive the output. 我尝试了一些递归选项,但最终实现了输出。
your a
and b
variable are not valid json. 您的
a
和b
变量无效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>
and a
will have structure like 和
a
将有类似的结构
{
id: 123
name: "john"
status: "inprocess"
transId: 245
}
I've used jquery api 我用过jQuery API
without jquery 没有jQuery
a={id:123,name:'john',status:'success'};
b={id:123,status:'inprocess',transId:245};
extend(a,b);
where extend function is: 扩展功能在哪里:
function extend(a, b){
for(var key in b)
if(b.hasOwnProperty(key))
a[key] = b[key];
return a;
}
It's simple 这很简单
for (var p in a)
b[p] = a[p];
let x = {
a: 1,
b: 2,
c: 3
}
let y = {
c: 4,
d: 5,
e: 6
}
let z = Object.assign(x, y)
console.log(z)
z:
{
a:1,
b:2,
c:4,
d:5,
e:6,
}
---> NOTICE : the object z take the y's c attribute --->注意:对象z具有y的c属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.