javascript - 将元素与对象数组匹配并推送到新数组
问题描述
假设我有一个对象数组,
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.
解决方案
如果我们要处理两个数组(特别是对于大数据集),将一个数组转换为对象(哈希)并遍历另一个数组以找到匹配项总是好的。
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))
推荐阅读
- c++ - 我不懂 C++ 中的 ++ 运算符
- actionscript-3 - Flash AS3 - 将多个对象拖放到多个目标
- c# - 如何正确地将我的 ContextMenu 命令绑定到 RelayCommand?
- javascript - 在 Jest 中使用 toBeCalledWith() 测试参数
- autohotkey - 使用自动热键激活组中最近活动的窗口
- python - __call__ 或 __init__ 在这里调用?不要不明白哪个和为什么
- amazon-web-services - s3 存储桶策略,例如从两个不同的帐户读取
- html - 每次我尝试触发更改事件时在 ie11 中接收脚本 70 错误
- python - python3元类的调用顺序
- python - 通过在每个索引处随机选取元素来合并 N 个列表