简体   繁体   中英

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.

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

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM