[英]Find intersection between two arrays of objects of different length
我有两个对象数组,它们共享一个具有相同名称( userId
)但长度不同的属性。 这是一个简单的例子:
const arr1= [
{
userId: "1",
name:"Tommy",
hobbies:"fighting"
},
{
userId: "16",
name:"Kino",
hobbies:"skating"
}
];
const arr2= [
{
userId: "1",
story:"Big fight"
},
{
userId:"16",
story:"big momentum"
}
];
我的理想结果是拥有一个数组,该数组将属性中匹配的两个对象与userId
(以及属性中匹配的所有对象)组合在一起,并保留两者的所有属性。
我试过使用concat
然后过滤,但无济于事。 关于如何实现这一点的任何线索或建议?
这可能是一个可能的解决方案:
const arr1 = [{userId: "1", name:"Tommy", hobbies:"fighting"}, {userId: "16", name:"Kino", hobbies:"skating"}]; const arr2 = [{userId: "1", story:"Big fight"}, {userId:"16", story:"big momentum"}]; const obj = [...arr1, ...arr2].reduce((acc, el) => { acc[el.userId] = {...acc[el.userId], ...el}; return acc; }, {}); const result = Object.values(obj); console.log(result);
我认为您需要执行以下操作:
function combByPropVal(){ const a = [].slice.call(arguments), prop = a.shift(), val = a.shift(), o = {}; a[0].forEach(obj=>{ if(prop in obj && obj[prop] === val){ o[prop] = val; for(let i in obj){ if(i !== prop)o[i] = obj[i]; } } }); return o; } const arr1 = [{userId: "1", name:"Tommy", hobbies:"fighting"}, {userId: "16", name:"Kino", hobbies:"skating"}]; const arr2 = [{userId: "1", story:"Big fight"}, {userId:"16", story:"big momentum"}]; console.log(combByPropVal('userId', '1', arr1.concat(arr2)));
combByPropVal
接受三个参数property
、 value
和一个Array of Objects
。 我使用.concat
在传入之前创建了一个新数组。
假设您有两个数组, arr1
和arr2
。 arr1
长度可能更长或等于arr2
。 arr2
和arr1
的对象之间的区别在于story
属性。
const arr1 = [
{ userId: "1", name: "Tommy", hobbies: "fighting" },
{ userId: "16", name: "Kino", hobbies: "skating" },
{ userId: "17", name: "Tom", hobbies: "Tennis" }
];
const arr2 = [
{ userId: "1", story: "Big fight" },
{ userId: "16", story: "big momentum" }
];
const result = arr1.map(obj1 => {
const obj2IfExist = arr2.find(obj2 => obj2.userId === obj1.userId);
obj1['story'] = obj2IfExist? obj2IfExist['story'] : null;
return obj1
})
console.log(result)
这就是你得到的:
[
{ userId: "1", name: "Tommy", hobbies: "fighting", story: "Big fight" },
{ userId: "16", name: "Kino", hobbies: "skating", story: "big momentum" },
{ userId: "17", name: "Tom", hobbies: "Tennis", story: null }
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.