Javascript - Условное свойство объекта - PullRequest
0 голосов
/ 05 сентября 2018

У меня есть следующие два массива:

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

Я хочу найти объект с userId == "myUID1" в arr2 и проверить, имеет ли он свойство children.

Поскольку arr2[1] равен userId == "myUID1" и имеет свойство children, я бы хотел добавить следующее свойство к arr1[0]:

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

Я хочу повторить это для всех объектов в arr1 и добавить свойство hasChildren к каждому из них, если в arr2 объект с таким же userId содержит свойство children.

Каков наилучший способ достичь желаемого результата?

1 Ответ

0 голосов
/ 05 сентября 2018

Самый простой способ - метод find () :

Метод find () возвращает значение первого элемента в массиве что удовлетворяет предоставленной функции тестирования. В противном случае не определено вернулся.

Но вы также можете сделать это, повторяя массив с каждым, forEach и т. Д.

Проверьте объясненный фрагмент:

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);
}
...