Javascript - 对象的条件属性

问题描述 投票:-1回答:1

我有以下两个数组:

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属性。

实现我想要的结果的最佳方法是什么?

javascript object conditional
1个回答
3
投票

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

find()方法返回数组中第一个满足提供的测试函数的元素的值。否则返回undefined。

但你也可以用每个,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);
}
© www.soinside.com 2019 - 2024. All rights reserved.