簡體   English   中英

比較兩個 arrays,從第一個到第二個有一個屬性,其中元素的 id 相同

[英]Comparing two arrays, have one property from first to second where id of element is same

我正在學習 javascript 並希望通過比較它們來處理兩個 arrays 並進行一些屬性合並:

我的 array1 和 array2 為:

array1 = [
          { id: 10, name: 'abc', otherData: 'other' },
          { id: 20, name: 'def', otherData: 'other' },
          { id: 30, name: 'ghi', otherData: 'other' },
        ];
array2 = [
          { id: 10, nameV2: 'xyz', otherData: 'other' },
          { id: 20, nameV2: 'pqr', otherData: 'other' },
          { id: 30, nameV2: 'tvs', otherData: 'other' },
        ];

我期待這個結果,我將比較 arrays,迭代元素,如果 id 相同,則在array1's元素中具有來自array2nameV2

預期 output:

array1 = [
          { id: 10, name: 'abc', otherData: 'other', nameV2: 'xyz' },
          { id: 20, name: 'def', otherData: 'other', nameV2: 'pqr' },
          { id: 30, name: 'ghi', otherData: 'other', nameV2: 'tvs' },
        ];

我應該如何做到這一點?

這是一種方法,我們使用 array2 創建一個查找映射 ( idNameV2Map ),然后使用它來獲取所需的 output

 const array1 = [{ id: 10, name: 'abc', otherData: 'other' }, { id: 20, name: 'def', otherData: 'other' }, { id: 30, name: 'ghi', otherData: 'other' }]; const array2 = [{ id: 10, nameV2: 'xyz', otherData: 'other' }, { id: 20, nameV2: 'pqr', otherData: 'other' },{ id: 30, nameV2: 'tvs', otherData: 'other' }]; const idNameV2Map = array2.reduce((acc, curr) => { acc[curr.id] = curr.nameV2; return acc; }, {}); const output = array1.map((item) => { if (idNameV2Map[item.id]) { return {...item, nameV2: idNameV2Map[item.id] }; } return item; }); console.log(output);

使用Array.find()的另一種方法
如果存在,則有條件地將nameV2屬性添加到 object 中。

 const array1 = [{ id: 10, name: 'abc', otherData: 'other' }, { id: 20, name: 'def', otherData: 'other' }, { id: 30, name: 'ghi', otherData: 'other' }]; const array2 = [{ id: 10, nameV2: 'xyz', otherData: 'other' }, { id: 20, nameV2: 'pqr', otherData: 'other' },{ id: 30, nameV2: 'tvs', otherData: 'other' }]; const output = array1.map((item) => { let objFound = array2.find(obj=>obj.id===item.id); return {...item, ...(objFound && {nameV2: objFound.nameV2}) }; }); console.log(output);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM