[英]Filtering for Multiple Fields in Object Array in Javascript/Lodash
I have the following array:我有以下数组:
PeopleList人物列表
[ {id:1, name:"Brian", status:"active"}, {id:2, name:"Mary", status:"active"},
{id:3, name:"John", status:"pending"}, {id:4, name:"Steph", status:"pending"},
{id:5, name:"Peter", status:"inactive"}
]
statusList状态列表
[ 'active', 'pending']
I want to filter the object array to only the statusList so I did the following:我想将对象数组过滤为仅 statusList,因此我执行了以下操作:
var filteredPeople =PeopleList.map(person => {
for (var i=0; i<=statusList.length; i++){
if(statusList[i] == person.active)
return {...person};
}
});
While the person objects return correctly, I also get "undefined" for objects that didn't pass the conditional statement.虽然 person 对象正确返回,但对于未通过条件语句的对象,我也会得到“未定义”。
So my result is:所以我的结果是:
[object, object, object,object, undefined ]
How can I make it so that if the conditional does not pass, I remove that object from the list?我怎样才能做到,如果条件不通过,我从列表中删除该对象?
Instead of map
you should use filter
for filtering array.您应该使用
filter
代替map
来过滤数组。 You can also use includes
.您还可以使用
includes
。
var data = [ {id:1, name:"Brian", status:"active"}, {id:2, name:"Mary", status:"active"}, {id:3, name:"John", status:"pending"}, {id:4, name:"Steph", status:"pending"}, {id:5, name:"Peter", status:"inactive"} ] var statusList = [ 'active', 'pending'] var result = data.filter(e => statusList.includes(e.status)) console.log(result)
With ES5 and older versions you can use indexOf
instead of includes
.在 ES5 和旧版本中,您可以使用
indexOf
而不是includes
。
var data = [ {id:1, name:"Brian", status:"active"}, {id:2, name:"Mary", status:"active"}, {id:3, name:"John", status:"pending"}, {id:4, name:"Steph", status:"pending"}, {id:5, name:"Peter", status:"inactive"} ] var statusList = [ 'active', 'pending'] var result = data.filter(function(e) { return statusList.indexOf(e.status) != -1 }) console.log(result)
var statusList = [];
var PeopleList = [
{ id: 1, name: "Brian", status: "active" },
{ id: 2, name: "Mary", status: "active" },
{ id: 3, name: "John", status: "pending" },
{ id: 4, name: "Steph", status: "pending" },
{ id: 5, name: "Peter", status: "inactive" }
];
for (var counter = 0; counter < PeopleList.length; counter++)
{
statusList.push(PeopleList[counter].status);
document.write(PeopleList[counter].status + "<br />");
}
// Here is your Status array
console.log(statusList);
// loop through all elements in your javascript status array and print them out
for (var i = 0; i < statusList.length; i++)
{
document.write("<strong>" + statusList[i] + "<br />");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.