Home > Blockchain >  Compare two arrays of objects; If second object contains the same key/value as the first return the
Compare two arrays of objects; If second object contains the same key/value as the first return the

Time:11-16

Consider the following: We have two arrays, each with an object.

let users: [
  {
    "id": "some#"
    "name": "some name",
    "data": "somedata"
  }
],


let products: [
    {
      "product": "some#"
      "name": "abc",
    },
]

Essentially compare both objects, if the second object has the same property as the first, keep the second prop and value if not add the prop/value from the first.

So the output is :

{
  "id": "some#",
  "name": "abc",
  "data": "somedata"
}

CodePudding user response:

Try this:

if (!(users[0].name === products[0].name)) {
product[0].data = users[0].data
}

CodePudding user response:

Hope that's what you are looking for :

let users= [
  {
    "id": "some#",
    "name": "some name",
    "data": "somedata",
  }
],


let products = [
    {
      "product": "some#",
      "name": "abc",
    },
]

for (key in users[0]) {
  if(products[0][key]){
    users[0][key] = products[0][key];
  }else{
    continue;
  }
}
console.log(users)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related