【问题标题】:Merge related objects from two arrays合并两个数组中的相关对象
【发布时间】:2018-03-04 16:16:09
【问题描述】:

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

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 的方式连接两个数组?

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

您可以将扩展语法与 .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 属性的值与回调中正在遍历的当前对象中的属性匹配。

有用的资源:

【讨论】:

    【解决方案2】:

    您可以连接数组。我假设您想从那里重新排序或修改您的键:值对,但将两个数组合二为一至少非常简单。

    var newArray = arr1.concat(arr2);
    

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

    【讨论】:

    • 他想合并两个数组的对象,而不是连接它们。
    【解决方案3】:

    你可以这样做:

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

    【讨论】:

      【解决方案4】:

      您可以使用 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; }

      【讨论】:

      • 您应该将此问题标记为明确重复,而不是一遍又一遍地生成similar answers
      猜你喜欢
      • 2016-12-15
      • 2016-03-08
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 2020-02-04
      • 2015-01-26
      相关资源
      最近更新 更多