合并两个数组中的相关对象

时间:2018-03-04 16:16:09

标签: javascript arrays object

我想合并两个数组中的相关对象。

var arr1 = [{thing: 'house', material: 'wood', location: 'earth'}, {thing: 'brick-wall', material: 'brick', location: 'moon'}];
var arr2 = [{property: 'made from wood', location: 'earth'}, {property: 'made from brick', location: 'moon'}];

是否可以以一种将arr2的属性值添加到arr1.location === arr2.location的arr1的方式加入这两个数组?

4 个答案:

答案 0 :(得分:3)

您可以使用.map().find()数组方法的扩展语法。

let arr1 = [
    {thing: 'house', material: 'wood', location: 'earth'},
    {thing: 'brick-wall', material: 'brick', location: 'moon'}
];
let arr2 = [
    {property: 'made from wood', location: 'earth'},
    {property: 'made from brick', location: 'moon'}
];

let result = arr1.map(o1 => ({
    ...o1, 
    property: arr2.find(o2 => o2.location === o1.location).property
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

或者,您可以使用Object.assign()

let arr1 = [
    {thing: 'house', material: 'wood', location: 'earth'},
    {thing: 'brick-wall', material: 'brick', location: 'moon'}
];
let arr2 = [
    {property: 'made from wood', location: 'earth'},
    {property: 'made from brick', location: 'moon'}
];

let result = arr1.map(o1 => Object.assign(
  {property: arr2.find(o2 => o2.location === o1.location).property}, o1
));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

说明

  • .map()将根据回调函数的结果创建一个新数组。
  • .find()将为我们提供第二个数组中的对象,其中location属性的值与回调中遍历的当前对象中的属性匹配。

有用的资源:

答案 1 :(得分:0)

您可以连接数组。我假设您想从那里重新订购或修改您的密钥:值对,但将这两个数组推入一个非常简单。

var newArray = arr1.concat(arr2);

这将生成一个名为“newArray”的新数组,但会保留现有的数组。

答案 2 :(得分:0)

你可以这样做:

arr1.map(i1 => 
  ({ ...i1, property: (arr2.find(i2 => i2.location === i1.location) || {}).property }));

答案 3 :(得分:0)

您可以使用Map并构建新对象



var arr1 = [{ thing: 'house', material: 'wood', location: 'earth' }, { thing: 'brick-wall', material: 'brick', location: 'moon' }],
    arr2 = [{ property: 'made from wood', location: 'earth' }, { property: 'made from brick', location: 'moon' }],
    map = new Map,
    result;

[arr1, arr2].forEach(a =>
    a.forEach(o => map.set(o.location, Object.assign(map.get(o.location) || {}, o))));

result = Array.from(map, ([k, v]) => v);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }