다음 배열이 있습니다.
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']
객체 배열을 statusList로만 필터링하고 싶으므로 다음을 수행했습니다.
var filteredPeople =PeopleList.map(person => {
for (var i=0; i<=statusList.length; i++){
if(statusList[i] == person.active)
return {...person};
}
});
사람 개체가 올바르게 반환되는 동안 조건문을 통과하지 못한 개체에 대해서도 "정의되지 않음"이 발생합니다.
그래서 내 결과는 다음과 같습니다.
[object, object, object,object, undefined ]
조건문이 통과되지 않으면 목록에서 해당 객체를 제거하려면 어떻게해야합니까?
대신 배열 필터링에 map
사용해야 filter
합니다. 당신은 또한 사용할 수 있습니다 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)
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)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다