我有以下两个数组:
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
属性。
实现我想要的结果的最佳方法是什么?
最简单的方法是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);
}