从键数组中查找对象数组
Find array of objects from keys array
我有一个对象数组
let objList = [
{
id:10,
...
},
{
id: 12,
...
},
{
id: 13,
...
},
...
];
我想过滤掉所有ID在另一个数组中的对象
let keyList = [10, 13];
Expected output:
[
{
id: 10,
...
},
{
id: 13,
...
}
]
注意:
The req. is in an Angular 7 application and I use Lodash library as well.
我试过:
objList.filter(eachObj => keysList.forEach(
eachID => {
eachID == eachObj['id']
}
))
和
find(ObjList, eachObj => {
return eachObj['id'] === keysList.map(eachID => {
return eachID;
})
})
您可以使用过滤器:
objList = objList.filter(element => keyList.indexOf(element.id) > -1);
你没有得到想要的结果,因为你没有从你的数组中得到 id
字段。
所以尝试使用 includes
方法并得到 id
属性:
const filteredArray = objList.filter(o => keyList.includes(o.id));
console.log(filteredArray);
使用_.differenceWith()
比较id
和key
,并删除两个数组中都存在的项目:
const objList = [{ id: 10 }, { id: 12 }, { id: 13 }];
const keyList = [10, 13];
const result = _.differenceWith(objList, keyList, ({ id }, key) => id === key);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.13/lodash.js"></script>
我有一个对象数组
let objList = [
{
id:10,
...
},
{
id: 12,
...
},
{
id: 13,
...
},
...
];
我想过滤掉所有ID在另一个数组中的对象
let keyList = [10, 13];
Expected output:
[
{
id: 10,
...
},
{
id: 13,
...
}
]
注意:
The req. is in an Angular 7 application and I use Lodash library as well.
我试过:
objList.filter(eachObj => keysList.forEach(
eachID => {
eachID == eachObj['id']
}
))
和
find(ObjList, eachObj => {
return eachObj['id'] === keysList.map(eachID => {
return eachID;
})
})
您可以使用过滤器:
objList = objList.filter(element => keyList.indexOf(element.id) > -1);
你没有得到想要的结果,因为你没有从你的数组中得到 id
字段。
所以尝试使用 includes
方法并得到 id
属性:
const filteredArray = objList.filter(o => keyList.includes(o.id));
console.log(filteredArray);
使用_.differenceWith()
比较id
和key
,并删除两个数组中都存在的项目:
const objList = [{ id: 10 }, { id: 12 }, { id: 13 }];
const keyList = [10, 13];
const result = _.differenceWith(objList, keyList, ({ id }, key) => id === key);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.13/lodash.js"></script>