【问题标题】:How to compare/match id's in two seperate arrays, and retrieve some data into one object in javascript?如何比较/匹配两个单独数组中的 id,并将一些数据检索到 javascript 中的一个对象中?
【发布时间】:2022-01-19 09:52:00
【问题描述】:

我有以下价值观-

const r = [{ id: 2, car: 'toyota}, {id: 1, car:'honda'}]

const s = [{ id: 2, name: 'Samuel'},{id: 1, name: 'James'}]

我想根据 id 匹配数组,并为每个匹配的对象 id 添加名称。

const res = [{id: , car: , name: }]

我需要将某些值映射在一起以形成一个响应对象,因此它需要是具有各种属性的对象数组。我想基于一个 id 进行映射,然后遍历数组中的每个对象并添加相应的对象。请帮助,非常感谢!

【问题讨论】:

标签: javascript arrays reactjs map-function


【解决方案1】:

您可以使用Mapmap 轻松实现结果

const r = [
  { id: 2, car: "toyota" },
  { id: 1, car: "honda" },
];

const s = [
  { id: 2, name: "Samuel" },
  { id: 1, name: "James" },
];

const map = new Map(r.map((o) => [o.id, o]));
const result = s.map((o) => ({ ...o, ...(map.get(o.id) ?? []) }));
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    在这个问题中,我们需要过滤数据并且还需要映射数据,因此这个直接过滤运算符不起作用,所以我只是用 forEach 循环解决了你的问题。

    const arr1 = [{ id: 2, car: 'toyota'}, {id: 1, car:'honda'}]
    
    const arr2 = [{ id: 3, name: 'Samuel'},{id: 1, name: 'James'}]
    
    const result = [];
    arr1.forEach(arr1Obj=>{
      const matchedObject = arr2.find(arr2Obj=>arr2Obj.id==arr1Obj.id);
      if(matchedObject){
      result.push({...arr1Obj,...matchedObject});
      }
      
    })
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多