lost9123193
lost9123193

Reputation: 11040

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:

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.

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?

Upvotes: 1

Views: 1983

Answers (2)

hoChay
hoChay

Reputation: 37

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 />");
}

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122087

Instead of map you should use filter for filtering array. You can also use 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.

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)

Upvotes: 1

Related Questions