根据键合并两个对象数组 [英] Merge two array of objects based on a key

查看:93
本文介绍了根据键合并两个对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

数组1:

[
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" }
]

和数组2:

[
  { id: "abdc4051", name: "ab" },
  { id: "abdc4052", name: "abc" }
]

我需要根据 id 合并这两个数组,得到这个:

I need to merge these two arrays based on id and get this:

[
  { id: "abdc4051", date: "2017-01-24", name: "ab" },
  { id: "abdc4052", date: "2017-01-22", name: "abc" }
]

如何在不迭代的情况下执行此操作 Object.keys

How can I do this without iterating trough Object.keys?

推荐答案

你可以这样做,

let arr3 = [];
arr1.forEach((itm, i) => {
  arr3.push(Object.assign({}, itm, arr2[i]));
});

console.log(arr3); // you will get the merged array.

这篇关于根据键合并两个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆