gpt4 book ai didi

javascript - JS - 将键附加到匹配的数组、对象值

转载 作者:行者123 更新时间:2023-12-02 23:52:16 24 4
gpt4 key购买 nike

我想将键值从 array2 的其他对象推送到 array1 中的对象

为此,它需要在两个数组中搜索相应的值,然后按右键。

let array1 = [
{
"Ref": "28189-060-B",
"Otherkey": "Whatever"
},
{
"Ref": "18182-250-B",
"Otherkey": "Whatever2"
},
{
"Ref": "55187-753-B",
"Otherkey": "Whatever3"
}
]

let array2 = [
{
"Ref": "28189-060-ABCD",
"Style": "Red"
},
{
"Ref": "18182-250-ABCD",
"Style": "Blue"
},
{
"Ref": "55187-753-ABCD",
"Style": "Yellow"
}
]

该函数需要循环遍历 array1 中的所有对象,查看 Ref 值的前 9 个字符,在 array2 Ref 中找到匹配项(只有前 9 个字符相同)。当匹配时将 array2 中的“Style”推送到 array1 中的相应对象

我尝试使用 Object.key.foreach()、map()、substr 只获取 9 个字符,使用 find()...所有这些都一团糟并且不起作用...

预期结果:

let array1 = [
{
"Ref": "18182-250-B",
"Otherkey": "Whatever2",
"Style": "Blue"
},
{
"Ref": "28189-060-B",
"Otherkey": "Whatever",
"Style": "Red"
},
{
"Ref": "55187-753-B",
"Otherkey": "Whatever3",
"Style": "Yellow"
}
]

最佳答案

假设这些属性全部是 Ref(有些是 Global_Style),您可以使用 forEachfind :

let array1 = [{"Ref":"28189-060-B","Otherkey":"Whatever"},{"Ref":"18182-250-B","Otherkey":"Whatever2"},{"Ref":"55187-753-B","Otherkey":"Whatever3"}];
let array2 = [{"Ref":"28189-060-ABCD","Style":"Red"},{"Ref":"18182-250-ABCD","Style":"Blue"},{"Ref":"55187-753-ABCD","Style":"Yellow"}];

const shorterRef = (ref) => ref.substr(0, 9);

array1.forEach(obj => {
const a1Ref = shorterRef(obj.Ref);
const arr2Obj = array2.find(tmp => shorterRef(tmp.Ref) === a1Ref);
if (arr2Obj) obj.Style = arr2Obj.Style;
});

console.log(array1);

如果您不想改变数组,请使用map:

let array1 = [{"Ref":"28189-060-B","Otherkey":"Whatever"},{"Ref":"18182-250-B","Otherkey":"Whatever2"},{"Ref":"55187-753-B","Otherkey":"Whatever3"}];
let array2 = [{"Ref":"28189-060-ABCD","Style":"Red"},{"Ref":"18182-250-ABCD","Style":"Blue"},{"Ref":"55187-753-ABCD","Style":"Yellow"}];

const shorterRef = (ref) => ref.substr(0, 9);

const out = array1.map(obj => {
const a1Ref = shorterRef(obj.Ref);
const arr2Obj = array2.find(tmp => shorterRef(tmp.Ref) === a1Ref);
if (arr2Obj) return { ...obj, Style: arr2Obj.Style };
});

console.log(out);

关于javascript - JS - 将键附加到匹配的数组、对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55587376/

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