gpt4 book ai didi

javascript - 将数据从一个数组复制到另一个数组

转载 作者:行者123 更新时间:2023-12-03 01:01:03 26 4
gpt4 key购买 nike

数组一:

 array1 = [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}]

数组二:

array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}]

结果数组:

 resultingArray =  [{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}],
"a_id" : {"id": 5, "name": "bcd"}
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}],
"a_id" : {"id": 4, "name": "bef"}
}]

我希望根据 array2 的 id 将 array2 对象添加到 array1 中。我尝试在两个数组上使用映射函数来比较和添加对象,但没有成功。你能告诉我该怎么做吗?

谢谢

最佳答案

根据array2的id将array2对象添加到array1中。

let array1 = 
[
{
"id": 1,
"name": "aaaaa",
"attr": [{"attr_code": "a_id", "value": "5"}]
},
{
"id": 2,
"name": "bbbbb",
"attr": [{"attr": "a_id", "value": "4"}]
}
];

let array2 = [{
"id": 4,
"name": "bef",
},
{
"id": 5,
"name": "bcd",
}
];

let resultingArray=[];

array1.forEach(function(element) {
element['a_id'] = [];
element['attr'].forEach(function(attr) {
element['a_id'].push(array2.find(function(item) {
return item.id == attr.value;
}));
});
resultingArray.push(element)
});

console.log(resultingArray);

关于javascript - 将数据从一个数组复制到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52619549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com