合并具有相同键的 2 个对象,来自 2 个数组的值

Bee*_*Bee 3 javascript arrays object node.js lodash

我想合并具有相同键的 2 个对象,来自 2 个数组的值,如下所示:

var arr1 = [
    { a: "a", 1: 1, 2: 2 },
    { a: "b", 1: 1, 2: 3 }
];

var arr2 = [
    { a: "a", 3: 123 },
    { a: "b", 3: 4411 }
];

var arr3 = _.map(arr1, function(a1) {
    var a3 = {};

    _.map(arr2, function(a2) {
        if (a1.a == a2.a) {
            a3 = _.extend(a1, a2);
        }
    })

    return a3
});
Run Code Online (Sandbox Code Playgroud)

结果:

arr3 = [ 
  { '1': 1, '2': 2, '3': 123, a: 'a' },
  { '1': 1, '2': 3, '3': 4411, a: 'b' } 
]
Run Code Online (Sandbox Code Playgroud)

它看起来很愚蠢吗?有没有其他方法可以做到这一点?谢谢阅读。

Ori*_*ori 8

使用lodash链Concat的阵列,类似的对象,然后合并各组的单个对象:

var arr1 = [{ a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 }];
var arr2 = [{ a: "a", 3: 123 }, { a: "b", 3: 4411 }];

var result = _(arr1)
  .concat(arr2) // concat the 2nd array
  .groupBy('a') // group by the identical key
  .map(_.spread(_.curry(_.merge, {}))) // left currey merge to to create a new empty object, and spread the group as parameters
  .value();
  
console.log(result);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

在 ES6 中,您可以使用Array#reduce收集Map 中的相似对象,然后获取Map#values迭代器,并使用spread 语法转换为数组:

const arr1 = [{ a: "a", 1: 1, 2: 2 }, { a: "b", 1: 1, 2: 3 }];
const arr2 = [{ a: "a", 3: 123 }, { a: "b", 3: 4411 }];

const result = [...arr1.concat(arr2) // concat the arrays
  .reduce((m, o) => m.set(o.a, Object.assign(m.get(o.a) || {}, o)), // use a map to collect similar objects
  new Map()
).values()]; // get the values iterator of the map, and spread into a new array
  
console.log(result);
Run Code Online (Sandbox Code Playgroud)

  • @Ajinkya - 我真的不知道告诉你真相。如果物品的数量很少,那其实并不重要。如果数量很大,你应该使用 lodash,因为点差不是堆栈安全的。您需要对其进行概要分析。 (2认同)