我有两个json对象obj1和obj2,我想将它们合并并创建一个json对象。结果json应该具有obj2中的所有值和obj2中不存在的obj1中的值。Question:var obj1 = { "name":"manu", "age":23, "occupation":"SE"}var obj2 = { "name":"manu", "age":23, "country":"india"}Expected:var result = { "name":"manu", "age":23, "occupation":"SE", "country":"india"}
3 回答
慕桂英546537
TA贡献1848条经验 获得超10个赞
使用Jquery的最简单方法-
var finalObj = $.extend(obj1, obj2);
没有Jquery-
var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];
RISEBY
TA贡献1856条经验 获得超5个赞
1)
var merged = {};
for(key in obj1)
merged[key] = obj1[key];
for(key in obj2)
merged[key] = obj2[key];
2)
var merged = {};
Object.keys(obj1).forEach(k => merged[k] = obj1[k]);
Object.keys(obj2).forEach(k => merged[k] = obj2[k]);
要么
Object.keys(obj1)
.concat(Object.keys(obj2))
.forEach(k => merged[k] = k in obj2 ? obj2[k] : obj1[k]);
3)最简单的方法:
var merged = {};
Object.assign(merged, obj1, obj2);
添加回答
举报
0/150
提交
取消