filter object properties javascript es6 code example
Example 1: js filter object of objects
// Our data
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
}
};
// Now let"s create a map function
const map = (obj, fun) =>
Object.entries(obj).reduce(
(prev, [key, value]) => ({
...prev,
[key]: fun(key, value)
}),
{}
);
// Finally let's map by color for example
const myFruits = map(fruits, (_, fruit) => fruit.color);
/*
{ apple: 'green',
banana: 'yellow',
orange: 'orange',
melon: 'yellow' }
/*
Example 2: 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);