假设我有以下包含对象数组(歌曲)的数组:
[
[
{
name: 'I Want You Back',
id: 1
},
{
name: 'ABC',
id: 2
}
],
[
{
name: 'I Want You Back',
id: 1
},
{
name: 'Dont Stop Me Now',
id: 3
}
],
[
{
name: 'I Want You Back',
id: 1
},
{
name: 'ABC',
id: 2
}
],
]
我希望浏览我的数据并返回每个数组中找到的对象,因此在这种情况下,返回值将是:
{
name: 'I Want You Back',
id: 1
}
到目前为止,我只设法为字符串阵列而不是对象这样做,例如:
const arrays = [
['I Want You Back', 'ABC'],
['I Want You Back', 'Dont stop me now'],
['I Want You Back', 'ABC']
];
const result = arrays.shift().filter((v) => {
return arrays.every((a) => {
return a.indexOf(v) !== -1;
});
});
// result = ["I Want You Back"]
我一直在尝试,但是我无法设法使用我的对象(例如它们的名称或ID)应用相同的逻辑。如果你们中有些人向我展示您将如何做。
您只能按唯一的 id
计数对象,然后浏览与数组长度相同的对象:
const songs = [[{name: 'I Want You Back',id: 1},{name: 'ABC',id: 2}],[{name: 'I Want You Back',id: 1},{name: 'Dont Stop Me Now',id: 3}],[{name: 'I Want You Back',id: 1},{name: 'ABC',id: 2}],]
// count of each unique id
let counts = songs.reduce((count, arr) => {
arr.forEach(obj => {
if (!count[obj.id]) count[obj.id] = {obj, count: 0}
count[obj.id].count += 1
})
return count
}, {})
// now filter out all whose count isn't the length
// and map to retreive just the object
let intersect = Object.values(counts)
.filter(o => o.count == songs.length)
.map(o => o.obj)
console.log(intersect)
当然,如果对象平等按值进行测试,这将容易得多,但是由于不是您需要跳过一些额外的篮球。