Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep only selected keys in every object from array

Tags:

javascript

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.

like image 732
barciewicz Avatar asked Feb 27 '19 14:02

barciewicz


1 Answers

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));
like image 89
Zenoo Avatar answered Sep 28 '22 07:09

Zenoo