JavaScript怎么把两个数组里的多个对象一一对应合并?

var obj1 = [{
  "id": 980550455852,
  "model": "XQG70-S1208FW",
  "color": "白",
  "invStatusName": "正品",
  "bactualQty": 10947,
  "brealyQty": 11000,
  "bavailQty": 53
}, {
  "id": 980550566221,
  "model": "XQB70-C3006",
  "color": "灰",
  "invStatusName": "正品",
  "bactualQty": 11,
  "brealyQty": 6,
  "bavailQty": -5
}];

var obj2 = [{
  "price": "6666"
}, {
  "price": "8888"
}];

上面是两个数组里面有对个对象,需求是把obj2中的每个价格和obj1里面的一一合并成一个对象,最后生成一个新的数组,是这种形式

[{
  "id": 980550455852,
  "model": "XQG70-S1208FW",
  "color": "白",
  "invStatusName": "正品",
  "bactualQty": 10947,
  "brealyQty": 11000,
  "bavailQty": 53,
  "price": "6666"
}, {
  "id": 980550566221,
  "model": "XQB70-C3006",
  "color": "灰",
  "invStatusName": "正品",
  "bactualQty": 11,
  "brealyQty": 6,
  "bavailQty": -5,
  "price": "8888"
}]

我现在是这样写的

var obj1 = [{
  "id": 980550455852,
  "model": "XQG70-S1208FW",
  "color": "白",
  "invStatusName": "正品",
  "bactualQty": 10947,
  "brealyQty": 11000,
  "bavailQty": 53
}, {
  "id": 980550566221,
  "model": "XQB70-C3006",
  "color": "灰",
  "invStatusName": "正品",
  "bactualQty": 11,
  "brealyQty": 6,
  "bavailQty": -5
}];
var obj2 = [{
  "price": "6666"
}, {
  "price": "8888"
}];
var obj3 = {};
Object.assign.apply(Object, [obj3].concat(obj1, obj2));
console.log(obj3);

结果成这样原来两个变成一个了,6666价格对应的对象没了

clipboard.png

阅读 8.4k
3 个回答

简洁的代码:

obj1.map((o,i) => { return {...o,...obj2[i]}})

比较好理解的代码:

//es2015实现合并对象函数代码
function assign(target, args) {
    if (target === null) return;
    if (Object.assign) {
        return Object.assign(target, args);
    } else {
        var _ = Object(target);
        for (var j = 1; j < arguments.length; j++) {
            var source = arguments[j];
            if (source) {
                for (var key in source) {
                    if (Object.prototype.hasOwnProperty.call(source, key)) {
                        _[key] = source[key];
                    }
                }
            }
        }
        return _;
    }
};

var result = obj1.map(function(o,index){
    return assign(o,obj2[index]);
})
var obj = obj1.map((o,index) => ({...o, ...obj2[index]}))

合并数组或者对象在数组或对象前面加...,是es6的新写法,然后数组的map方法会返回数组.

var obj1 = [{
  "id": 980550455852,
  "model": "XQG70-S1208FW",
  "color": "白",
  "invStatusName": "正品",
  "bactualQty": 10947,
  "brealyQty": 11000,
  "bavailQty": 53
}, {
  "id": 980550566221,
  "model": "XQB70-C3006",
  "color": "灰",
  "invStatusName": "正品",
  "bactualQty": 11,
  "brealyQty": 6,
  "bavailQty": -5
}];

var obj2 = [{
  "price": "6666"
}, {
  "price": "8888"
}];
var obj = obj1.map((item,index) => {
    return {...item, ...obj2[index]};
});
console.log(obj);

结果如下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题