首页 > 解决方案 > 将元素与对象数组匹配并推送到新数组

问题描述

假设我有一个对象数组,

const attachmentData = [{name: 'Suman Baidh',attachment: ["123","456"]},
                        {name: 'John Sigma',attachment: ["789","101112]},
                        {name: 'Binay', attachment: ["131415","161718","192021]}]

另一个对象数组,

const attachmentDetail = [{"id":"123",details:{"cost":10,"quantity":20}},
                          {"id":"456",details: {"cost":15,"quantity":28}},
                          {"id":"789",details:{"cost":4,"quantity":9}},
                          {"id":"101112",details:{"cost":40,"quantity":2}},
                          {"id":"131415",details:{"cost":12,"quantity":9}},
                          {"id":"161718",details:{"cost":45,"quantity":2}},
                          {"id":"192021",details:{"cost":120,"quantity":1}}]

我希望 O/P 为:这样与 attachmentDetail 匹配的 id 也有 name 并推送到新数组。

      [{"name":"Suman Baidh","id":"123","cost":10,"quantity":20},
       {"name":"Suman Baidh","id":"456","cost":15,"quantity":28},
       {"name":"John Sigma","id":"789","cost":4,"quantity":9} ,
       {"name":"John Sigma","id":"101112","cost":40,"quantity":2}, 
       {"name":"Binay","id":"131415","cost":12,"quantity":9}, 
       {"name":"Binay","id":"161718","cost":45,"quantity":2}, 
       {"name":"Binay","id":"192021","cost":120,"quantity":1}]

为此,我尝试了,

let newArray = []
for(let i = 0;i<attachmentData.length;i++)}{
    for(let j = 0;j<attachmentData[i].attachment.length;j++){
        if(attachmentData[i].attachment[j] == attachmentDetail.id){
            newArray.push(...attachmentData[i], ... attachmentData[i].attachment[j]
        }
    }
}

On console.log(newArray) , its giving me not the answer I wanted. 

If anyone needs any further information, please let me know. Any suggestion would be really helpful.

标签: javascriptnode.js

解决方案


如果我们要处理两个数组(特别是对于大数据集),将一个数组转换为对象(哈希)并遍历另一个数组以找到匹配项总是好的。

const attachmentData = [{name: 'Suman Baidh',attachment: ["123","456"]}, {name: 'John Sigma',attachment: ["789","101112"]}, {name: 'Binay', attachment: ["131415","161718","192021"]}]
const attachmentDetail = [{"id":"123",details:{"cost":10,"quantity":20}}, {"id":"456",details: {"cost":15,"quantity":28}}, {"id":"789",details:{"cost":4,"quantity":9}}, {"id":"101112",details:{"cost":40,"quantity":2}}, {"id":"131415",details:{"cost":12,"quantity":9}}, {"id":"161718",details:{"cost":45,"quantity":2}}, {"id":"192021",details:{"cost":120,"quantity":1}}];
  
  function customMerge(data, attachments) {
  
    const hashById = attachments.reduce((acc, ele) => {
      acc[ele.id] = ele;
      return acc;
    }, {});

    return data.reduce((acc, {attachment, name}) => {
            return acc.concat(attachment.map(id => ({name, id, details: hashById[id].details})));
    },[]);
  }
  
  console.log(customMerge(attachmentData, attachmentDetail))


推荐阅读