欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-17 13:05:50
...
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"
}];

简洁的代码:

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

比较好理解的代码:

//es2015实现合并对象函数代码


```javascript
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]);
})

方法2:

obj1.sort((a,b) => { return b.id - a.id });

文章是转载的 。原文链接~~
https://segmentfault.com/q/1010000019520120