gpt4 book ai didi

javascript - 如何使用另一个 JS 数组替换 JS 数组属性值

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

我想使用另一个 JS 数组替换 JS 数组属性值。我解释如下。

const arr1 = [
{
code: "XXY",
dis: "cont1",
note: "Note for cont1"
},
{
code: "AAW",
dis: "cont2",
note: "Note for cont2"
},
{
code: "TTR",
dis: "cont5",
note: "Note for cont5"
},
{
code: "MMN",
dis: "cont10",
note: "Note for cont10"
}]
const new_array = [
{
"code": "AAW",
"dis": "cont2 new",
"note": "Note for cont2"
},
{
"code": "TTR",
"dis": "cont5",
"note": "New Note for cont5"
}]
预期输出:
[
{
code: "XXY",
dis: "cont1",
note: "Note for cont1"
},
{
code: "AAW",
dis: "cont2 new",
note: "Note for cont2"
},
{
code: "TTR",
dis: "cont5",
note: "New Note for cont5"
},
{
code: "MMN",
dis: "cont10",
note: "Note for cont10"
}
]
我们需要检查所有 arr1元素等于 new_arr.codearr1.code并比较 disnote特性。如 arr1.dis不等于 new_arr.dis然后 arr1.dis值应替换为 new_arr.dis .这与 note 相同属性(property)也。
试过的代码:
arr1.forEach(function(item1) {
var item2 = arr1.find(function (item2) {
return arr1.code === new_array.code;
});
})

console.log(arr1);
电流输出:
[
{
"code": "XXY",
"dis": "cont1",
"note": "Note for cont1"
},
{
"code": "AAW",
"dis": "cont2",
"note": "Note for cont2"
},
{
"code": "TTR",
"dis": "cont5",
"note": "Note for cont5"
},
{
"code": "MMN",
"dis": "cont10",
"note": "Note for cont10"
}
]
我该如何解决这个问题?

最佳答案

new_array.forEach(o1 => { // for every replacement object
// find the corresponding object in the original array
const found = arr1.find(o2 => o2.code === o1.code);
// if there is a corresponding object
if (found) {
// copy its properties over
found.dis = o1.dis;
found.note = o1.note;
}
})
注意这里有一个很差的 O(n^2)时间复杂度,如果您有一个大型数据集,请考虑使用其他答案推荐的集合进行更快的查找。

关于javascript - 如何使用另一个 JS 数组替换 JS 数组属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64573679/

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