EDIT: not a duplicate, as my question does not ask for deleting a specific key, but all keys not found in an array.
In the below, function redux1
removes entries corresponding to keys not listed in keys_to_keep
from data
object.
Given that I have a list of object keys to keep, how can I rewrite redux1
in a cleaner way, prefarably utilizing map
, filter
or reduce
?
var data = [
{name: 'John', city: 'London', age: 42},
{name: 'Mike', city: 'Warsaw', age: 18},
{name: 'Jim', city: 'New York', age: 22},
{name: 'Celine', city: 'Tokyo', age: 54},
]
var keys_to_keep = ['name', 'city']
function redux1(data) {
data.forEach((person) => {
Object.keys(person).forEach((key) => {
if (!keys_to_keep.includes(key)) {
delete (person[key])
}
})
})
console.log(data)
}
function redux2(data) {
var reduced = data.filter(person => Object.keys(person).filter(key => keys_to_keep.includes(key)))
console.log(reduced)
}
redux1(data)
//redux2(data)
My current redux2
will return objects will not remove age
.
You could use a combination of Array#map
and Array#reduce
:
const data = [
{name: 'John', city: 'London', age: 42},
{name: 'Mike', city: 'Warsaw', age: 18},
{name: 'Jim', city: 'New York', age: 22},
{name: 'Celine', city: 'Tokyo', age: 54},
]
const keys_to_keep = ['name', 'city'];
const redux = array => array.map(o => keys_to_keep.reduce((acc, curr) => {
acc[curr] = o[curr];
return acc;
}, {}));
console.log(redux(data));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With