Example 1: how to filter object in javascript
let arr = [
{name: "John", age: 30},
{name: "Grin", age: 10},
{name: "Marie", age: 50},
];
let newArr = arr.filter((person)=>(return person.age <= 40));
Example 2: js filter object
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;
};
var obj = {
name : 'john',
lastName : 'smith',
age : 32
}
var filteredObj = filterObj( obj, function( key, value ) {
return key !== 'age' && value !== 'smith'
});
console.log( filteredObj );
Example 3: can filter be used on objects in javascript
var heroes = [
{name: “Batman”, franchise: “DC”},
{name: “Ironman”, franchise: “Marvel”},
{name: “Thor”, franchise: “Marvel”},
{name: “Superman”, franchise: “DC”}
];
var marvelHeroes = heroes.filter(function(hero) {
return hero.franchise == “Marvel”;
});
Example 4: filter in js
const filterThisArray = ["a","b","c","d","e"]
console.log(filterThisArray)
const filteredThatArray = filterThisArray.filter((item) => item!=="e")
console.log(filteredThatArray)
Example 5: filter out arrays js
let newArray = array.filter(function(item) {
return condition;
});
Example 6: js filter object of objects
const fruits = {
apple: {
qty: 300,
color: "green",
name: "apple",
price: 2
},
banana: {
qty: 130,
color: "yellow",
name: "banana",
price: 3
},
orange: {
qty: 120,
color: "orange",
name: "orange",
price: 1.5
},
melon: {
qty: 70,
color: "yellow",
name: "melon",
price: 5
}
};
const map = (obj, fun) =>
Object.entries(obj).reduce(
(prev, [key, value]) => ({
...prev,
[key]: fun(key, value)
}),
{}
);
const myFruits = map(fruits, (_, fruit) => fruit.color);