合并数组js

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

我有一个数据数组:

[
   { name: '1', goalsTable: 6544b8a5fea0bf50fc0c62fb },
   { name: '1fork', goalsTable: 6548740f05dc440b5c61c5ac }
]

我有一个目标数据数组:

[
   {
     _id: 6544b8a5fea0bf50fc0c62fb,
     tableData: [ [Object], [Object], [Object], [Object] ],
     goalsData: { qty: 12 }
   },
   {
     _id: 6548740f05dc440b5c61c5ac,
     tableData: [ [Object], [Object], [Object], [Object], [Object] ],
     goalsData: { qty: 10 }
   }
 ]

我想要的是如果 id 彼此匹配则合并对象。例如,如果目标数据的第一个对象的_id与数据的目标表匹配,则数据对象变为:

[{
   name: '1', 
   goalsTable: 6544b8a5fea0bf50fc0c62fb, 
   tableData: [ [Object], [Object], [Object], [Object] ], 
   goalsData: { qty: 12 } 
}]
javascript arrays javascript-objects
1个回答
0
投票

我设法通过将两个数组映射到另一个数组来解决这个问题。找到 Id 后,我将特定值添加到第一个数组中

let arr = [{
    name: "1",
    goalsTable: "6544b8a5fea0bf50fc0c62fb"
  },
  {
    name: "1fork",
    goalsTable: "6548740f05dc440b5c61c5ac"
  },
];

let arr2 = [{
    _id: "6544b8a5fea0bf50fc0c62fb",
    tableData: [
      [Object],
      [Object],
      [Object],
      [Object]
    ],
    goalsData: {
      qty: 12
    },
  },
  {
    _id: "6548740f05dc440b5c61c5ac",
    tableData: [
      [Object],
      [Object],
      [Object],
      [Object],
      [Object]
    ],
    goalsData: {
      qty: 10
    },
  },
];

let newarray = arr.map((value, index) => {
  arr2.map((value2, index2) => {
    if (value.goalsTable == value2._id) {
      arr[index]["_id"] = value2._id;
      arr[index]["tableData"] = value2.tableData;
      arr[index]["goalsData"] = value2.goalsData;
    }
  });
});

console.log(arr);

© www.soinside.com 2019 - 2024. All rights reserved.