[英]How to compare property in two different objects and operate on it?
a= [{
"id": "567",
"username": "foo",
"profile_title": "Senior Analyst"
},
{
"id": "123",
"username": "bar",
"profile_title": "Program Management"
}]
b= [{
"URL": "https://abcd.com",
"id": "123"
},
{
"URL": "https://efgh.com",
"id": "456"
}]
I have two arrays with objects, I need to compare id and if they match, need to copy URL property from b to a.我有两个数组与对象,我需要比较ID,如果他们匹配,需要URL属性从B复制到。
You can achieve this by the following code.您可以通过以下代码实现此目的。
a.map((a_item, a_index) => {
b.some((b_item, b_index) => {
if(a_item.communityid === b_item.communityid){
a[a_index].URL = b[b_index].URL;
}
})
})
Simply you can use for
loop
只需您可以使用
for
loop
var a= [{ "communityid": "2032", "username": "foo", "profile_title": "Senior Analyst" }, { "communityid": "2085", "username": "bar", "profile_title": "Program Management" }]; var b= [{ "URL": "https://abcd.com", "communityid": "2032" }, { "URL": "https://efgh.com", "communityid": "2085" }]; for(i in a){ for(j in b){ if(a[i].communityid == b[j].communityid){ a[i].URL = b[j].URL; } } } console.log(a);
For simple understanding and static comparison try this, you can use a recursive method to loop through it once you understood it.为了简单理解和静态比较试试这个,你可以使用递归方法在你理解它之后循环它。
let fun = ()=>
{
if(a[0].username == b[0].usernmame)
{
return "Matched!"
}
else{
return "Bad luck!"
}
}
console.log(fun());
key element: a[0].username == b[0].usernmame,a[1].username == b[1].usernmame etc关键元素:a[0].username == b[0].usernmame,a[1].username == b[1].usernmame 等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.