Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript filter array of objects

I have an array of objects and I'm wondering the best way to search it. Given the below example how can I search for name = "Joe" and age < 30? Is there anything jQuery can help with or do I have to brute force this search myself?

var names = new Array();  var object = { name : "Joe", age:20, email: "[email protected]"}; names.push(object);  object = { name : "Mike", age:50, email: "[email protected]"}; names.push(object);  object = { name : "Joe", age:45, email: "[email protected]"}; names.push(object); 
like image 231
user441521 Avatar asked Nov 27 '12 23:11

user441521


People also ask

Can you filter an array of objects in JavaScript?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How do you filter two arrays of objects?

Filter an array containing objects based on another array containing objects in JavaScript. const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}]; const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];

Can you filter through an object JavaScript?

JavaScript objects don't have a filter() method, you must first turn the object into an array to use array's filter() method. You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below.


1 Answers

A modern solution with Array.prototype.filter():

const found_names = names.filter(v => v.name === "Joe" && v.age < 30); 

Or if you still use jQuery, you may use jQuery.grep():

var found_names = $.grep(names, function(v) {     return v.name === "Joe" && v.age < 30; }); 
like image 150
VisioN Avatar answered Oct 21 '22 09:10

VisioN