如何在不使用JQUERY的情况下联接两个JavaScript对象

我有两个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"

}


泛舟湖上清波郎朗
浏览 427回答 3
3回答

慕桂英546537

使用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

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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript