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: