Smitherson
Smitherson

Reputation: 423

Javascript - Conditional property on object

I have the following two arrays:

let arr1 = [{userId:"myUID1", name: "Dave"},{userId: "myUID2", name: "John"}]
let arr2 = [{userId: "myUID3", dogs: 5}, {userId:"myUID1", children: 0}]

I want to find the object with userId == "myUID1" in arr2 and check whether it has the property children.

Since arr2[1] is userId == "myUID1" and has children property I would like to add the following property to arr1[0]:

let arr1 = [{userId:"myUID1", name: "Dave", hasChildren: true},{userId: "myUID2", name: "John"}]

I wish to repeat this for all objects in arr1 and add the hasChildren property to each one of them if in arr2 the object with the same userId holds a children property.

What would be the best way to achieve the result I desire?

Upvotes: 0

Views: 87

Answers (1)

The simplest way is the find() method:

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

But you can also do it iterating the array with each, forEach, etc.

Check the explained snippet:

let arr1 = [{userId:"myUID1", name: "Dave"},{userId: "myUID2", name: "John"}];
let arr2 = [{userId: "myUID3", dogs: 5}, {userId:"myUID1", children: 0}];

//first we find the item in arr2. The function tells what to find.
var result2 = arr2.find(function(item){return (item.userId == "myUID1");});

//if it was found...
if (typeof result2 === 'object') {
  //we search the same id in arr1 
  var result1 = arr1.find(function(item){return (item.userId == result2.userId);});
  //and add the property to that item of arr1
  result1.hasChildren=true;
  
  //and print it, so you can see the added property
  console.log (arr1);
}

Upvotes: 3

Related Questions