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: javascript object filter
function objectFilter = (obj, predicate) =>
Object.keys(obj)
.filter( key => predicate(obj[key]) )
.reduce( (res, key) => (res[key] = obj[key], res), {} );
var scores = {
John: 2, Sarah: 3, Janet: 1
};
var filtered = objectFilter(scores, num => num > 1);
console.log(filtered);
Example 3: 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 4: 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);
Example 5: Object properties filter from properties js
const raw = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
const allowed = ['item1', 'item3'];
const filtered = Object.keys(raw)
.filter(key => allowed.includes(key))
.reduce((obj, key) => {
obj[key] = raw[key];
return obj;
}, {});
console.log(filtered);