假设我有一个userIds数组
const userIds = ['1234', '3212', '1122']
然后我有一个对象数组
const arrayOfObjects = [
{
_source: {itemId: ['1234'] }
},
{
_source: {itemId: ['3212'] }
},
{
_source: {itemId: ['1111'] }
}
]
我想通过将id与userIds数组匹配来过滤对象数组
arrayOfObjects.filter(item => item._source.itemId === "what goes here?")
答案 0 :(得分:3)
尝试一下
arrayOfObjects.filter(item => userIds.includes(item._source.itemId[0]))
答案 1 :(得分:1)
Array.prototype.includes
。如果需要跨浏览器解决方案,则可以使用Array.prototype.filter
和Array.prototype.indexOf
方法:
const userIds = ['1234', '3212', '1122'];
const arrayOfObjects = [{
_source: {
itemId: ['1234']
}
},
{
_source: {
itemId: ['3212']
}
},
{
_source: {
itemId: ['1111']
}
}
];
const filtered = arrayOfObjects.filter(o => userIds.indexOf(o['_source'].itemId[0]) > -1);
console.log(filtered)