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

问题描述 投票:0回答:4

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

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的方式加入这两个数组,其中arr1.location === arr2.location

javascript arrays object
4个回答
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属性的值与回调中遍历的当前对象中的属性匹配。

有用的资源:


0
投票

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

var newArray = arr1.concat(arr2);

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


0
投票

你可以这样做:

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

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; }
© www.soinside.com 2019 - 2024. All rights reserved.