Javascript - 对象上的条件 属性

Javascript - Conditional property on object

我有以下两个数组:

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

我想在arr2中找到带有userId == "myUID1"的对象,并检查它是否有属性 children

由于 arr2[1]userId == "myUID1" 并且有 children 属性 我想将以下 属性 添加到 arr1[0]:

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

我希望对 arr1 中的所有对象重复此操作,如果在 arr2 中具有相同 userId 持有 children 属性.

达到我想要的结果的最佳方法是什么?

最简单的方法是find()方法:

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

但您也可以使用 each、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);
}