我有一个包含ID的数组和包含在数组中的相同ID的对象列表,如何从数组ID中删除基于对象的对象?
数组:
displayGroups
对象列表:
user_ids: [“id001”, “id004”]
所以结果将是:
{
{
“user_id”: “id001”,
“city”: “Seattle”
},
{
“user_id”: “id002”,
“city”: “Los Angeles”
},
{
“user_id”: “id003”,
“city”: “San Francisco”
},
{
“user_id”: “id004”,
“city”: “San Diego”
}
}
答案 0 :(得分:1)
数组方法
Array.prototype.filter()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
filter()方法创建一个新数组,该数组包含所有通过提供的功能实现的测试的元素。
Array.prototype.includes()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
includes()方法确定数组是否包含某个元素,并在适当时返回true或false。
let user_ids = ["id001", "id004"];
let list = [
{
"user_id": "id001",
"city": "Seattle"
},
{
"user_id": "id002",
"city": "Los Angeles"
},
{
"user_id": "id003",
"city": "San Francisco"
},
{
"user_id": "id004",
"city": "San Diego"
}
];
console.log(list.filter( o => !(user_ids.includes(o.user_id)) ));
答案 1 :(得分:0)
如果对象列表是数组,则可以这样:
for (var i = 0;i<object_list.length;i++){
if (object_list[i]["user_id"] in user_ids){
object_list.splice(i, 1);
}
}
如果它是一个对象,则可以通过以下方式完成:
for (var i in object_list){
if (object_list[i]["user_id"] in user_ids){
delete object_list[i];
}
}