【问题标题】:How to add values from one array of object to another?如何将一个对象数组中的值添加到另一个对象?
【发布时间】:2021-02-20 19:59:53
【问题描述】:

我正在尝试获取一个数组,其中所有值都包含在 arr1 和 arr2 中。但我无法达到最终结果。

arr1 = [
  {
    region: "Total",
    population: 15200100,
    first: 42999
  }
]

arr2 = [
  {
    region: "Total",
    second: 2939
  }
]

output = [
  {
    region: "Total",
    population: 15200100,
    first: 42999
    second: 2939
  }
]

【问题讨论】:

  • 嗯,顺便说一句,每个 arr 中的所有键(region 之类的东西)是唯一的吗?

标签: javascript arrays json object iteration


【解决方案1】:

一行:

const arr1 = [ { region: "Total", population: 15200100, first: 42999 } ];
const arr2 = [ { region: "Total", second: 2939 } ];
const res = arr1.map((_, index) => ({ ...arr1[index], ...arr2[index] }));

console.log(res);

【讨论】:

    【解决方案2】:

    试试这个:

    const arr1 = [ { region: "Total", population: 15200100, first: 42999 } ];
    const arr2 = [ { region: "Total", second: 2939 } ];
    const res = [];
    
    for(let i = 0; i < arr1.length || i < arr2.length; i++) {
      const first = arr1[i] || {};
      const second = arr2[i] || {};
      res[i] = { ...first, ...second };
    }
    
    console.log(res);

    【讨论】:

      【解决方案3】:

      下面的示例在找到相似键时返回一个总和。

      const arr1 = [{
        region: "Total",
        population: 15200100,
        first: 42999
      }];
      const arr2 = [{
        region: "Total",
        second: 2939
      }];
      const arr3 = [{
        region: "Total",
        population: 15200100,
        first: 42999
      }];
      const arr4 = [{
        region: "Total",
        first: 3243,
        second: 2939,
        third: 32
      }];
      function test(arr1,arr2) {
        let res = Array.from(arr1);
        res.forEach((x) => {
          arr2.forEach((y) => {
            for (let key in y) {
              if (typeof x[key] == 'undefined') {
                x[key] = y[key];
              } else {
                if (key !== 'region') {
                  x[key] += y[key];
                }
              }
            }
          });
        });
        return res;
      }
      
      console.log(test(arr1,arr2));
      console.log(test(arr3,arr4));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-30
        • 1970-01-01
        • 2022-08-13
        • 1970-01-01
        • 2021-03-24
        • 2021-07-14
        • 2021-12-28
        • 1970-01-01
        相关资源
        最近更新 更多