Javascript-对象的条件属性

时间:2018-09-04 21:52:09

标签: javascript object conditional

我有以下两个数组:

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 :(得分:3)

最简单的方法是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);
}