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);
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.
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'}];
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.
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With