javascript filter array of objects by key code example
Example 1: how to filter an array of objects in javascript
let arr=[{id:1,title:'A', status:true}, {id:3,title:'B',status:true}, {id:2, title:'xys', status:true}];
//find where title=B
let x = arr.filter((a)=>{if(a.title=='B'){return a}});
console.log(x)//[{id:3,title:'B',status:true}]
Example 2: javascript filter array of objects by key
var data = { records : [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] }
var empIds = [1,4,5]
var filteredArray = data.records.filter(function(itm){
return empIds.indexOf(itm.empid) > -1;
});
filteredArray = { records : filteredArray };
Example 3: js filter object
/** filter object by key or value */
/** filter object function */
function filterObj( obj, predicate ) {
var result = {}, key;
for ( key in obj ) {
if ( obj.hasOwnProperty( key ) && predicate( key, obj[ key ] ) ) {
result[ key ] = obj[ key ];
}
}
return result;
};
// example
// set object
var obj = {
name : 'john',
lastName : 'smith',
age : 32
}
// filter out parameters using key and value
var filteredObj = filterObj( obj, function( key, value ) {
return key !== 'age' && value !== 'smith'
});
// show result
console.log( filteredObj ); // { name: "john" }
Example 4: does filter change original array
Note: filter() does not change the original array.