I would like to transform the follow array into a slightly modified object (see below). I'm also trying to practice using the spread operator, but haven't been able to figure out how to do it. I'm trying to avoid using lodash (for educational purposes).
Starting array:
var arr = [
{ mainkey: 'John', val1: 'ABC', val2: '..', val3: '..' },
{ mainkey: 'Mary', val1: 'DEF', val2: '..', val3: '..' },
{ mainkey: 'Ann', val1: 'XYZ', val2: '..', val3: '..' }
];
to final object:
newObj = {
John: {val1: 'ABC', val2: '..', val3: '..' },
Mary: {val1: 'DEF', val2: '..', val3: '..' },
Ann: {val1: 'XYZ', val2: '..', val3: '..' }
}
Without using the spread operator, this gets close, but not where I need to be:
var result = arr.reduce(function(map, obj) {
map[obj.mainkey] = obj.val1;
// map[obj.mainkey] = { obj.val1, obj.val2 }; <-- DOESNT WORK
return map;
}, {});
With the spread operator anything I do fails.
Other posts with helpful content:
Short answer
Explained
We're calling
Array.prototype.reduce()
, and for each object within the array, deconstructingmainkey
from the rest of the properties (somainkey
could be John andrest
could be something like this:{val1: 'ABC', val2: '..', val3: '..' }
.Then, we want to return the accumulator with a deep change, so we use the spread operator, followed by setting the the interploated
mainkey
property ([mainkey]
) to berest
.