javascript filter array of objects
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;
});
var nameList = [
{name:'x', age:20, email:'[email protected]'},
{name:'y', age:60, email:'[email protected]'},
{name:'Joe', age:22, email:'[email protected]'},
{name:'Abc', age:40, email:'[email protected]'}
];
var filteredValue = nameList.filter(function (item) {
return item.name == "Joe" && item.age < 30;
});
//To See Output Result as Array
console.log(JSON.stringify(filteredValue));
You can simply use javascript :)
You could utilize jQuery.filter() function to return elements from a subset of the matching elements.
var names = [
{ name : "Joe", age:20, email: "[email protected]"},
{ name : "Mike", age:50, email: "[email protected]"},
{ name : "Joe", age:45, email: "[email protected]"}
];
var filteredNames = $(names).filter(function( idx ) {
return names[idx].name === "Joe" && names[idx].age < 30;
});
$(filteredNames).each(function(){
$('#output').append(this.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"/>
You can do this very easily with the [].filter
method:
var filterednames = names.filter(function(obj) {
return (obj.name === "Joe") && (obj.age < 30);
});
You can learn more about it on this MDN page.