gpt4 book ai didi

javascript - 比较两个对象数组并向匹配的对象添加新属性

转载 作者:太空宇宙 更新时间:2023-11-04 16:26:10 25 4
gpt4 key购买 nike

我有两个像这样的对象数组:

let data1 = [ { userid_b: 'dan12345' }, { userid_b: 'emma12345' } ]
let data2 =[
{ username: 'dan', userid: 'dan12345' },
{ username: 'johndoe', userid: 'john12345' },
{ username: 'emma', userid: 'emma12345' },
{ username: 'Bob', userid: 'bob12345' },
{ username: 'Sam', userid: 'sam12345' }
]

我想比较userid_buserid这两个,如果它们相同,我想向data2添加一个新属性。

所以我想要这样的结果:

let data2 =[ 
{ username: 'dan', userid: 'dan12345', newAttribute: true },
{ username: 'johndoe', userid: 'john12345' },
{ username: 'emma', userid: 'emma12345', newAttribute: true },
{ username: 'Bob', userid: 'bob12345' },
{ username: 'Sam', userid: 'sam12345' }
]

我怎样才能实现这个目标?

最佳答案

循环两个数组并比较值,必要时进行赋值:

var data1 = [
{ userid_b: 'dan12345' },
{ userid_b: 'emma12345' }
];

var data2 = [
{ username: 'dan', userid: 'dan12345' },
{ username: 'johndoe', userid: 'john12345' },
{ username: 'emma', userid: 'emma12345' },
{ username: 'Bob', userid: 'bob12345' },
{ username: 'Sam', userid: 'sam12345' }
];

// Loop the main array
for (var i = 0; i < data2.length; i++) {
// Loop the second array
for (var j = 0; j < data1.length; j++) {
// If the user id matches
if (data2[i].userid == data1[j].userid_b) {
// Add the attribute
data2[i].newAttribute = true;
// Break out of the the 'j' loop to stop unnecessary iterations
break;
}
}
}

console.log(data2);

关于javascript - 比较两个对象数组并向匹配的对象添加新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40198802/

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