Keep only selected keys in every object from array

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.


Solution 1:

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));

Solution 2:

use Array.map and Array.forEach inside it :

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']

const result = data.map(e => {
  const obj = {};
  keys_to_keep.forEach(k => obj[k] = e[k])
  return obj;
});

console.log(result);

Solution 3:

A version slightly shorter than the accepted answer using Array#map and Object.fromEntries():

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 redux1 = list => list.map(o => Object.fromEntries(
    keys_to_keep.map(k => [k, o[k]])
));

console.log(redux1(data));