Reputation: 1301
Essentially I have an array such as:
var q = [ { box: false, name: 'A1', stats: ['average'] },
{ box: false, name: 'A2', stats: ['min', 'max'] } ]
I want to turn this array into
{ A1: ['average'], A2: ['min', 'max'] }
I tried using reduce IE:
_.reduce(q, function(statHash, val) {
return _.extend(statHash, {val.name: val.stats}) }, {})
Now this didn't work because I couldn't reference val.name as the key to the object (as well as me possibly not passing the memo correctly for reduce..)
What is the simplest way to transform an array of that kind into that object?
Upvotes: 2
Views: 46
Reputation: 4506
The logic of your solution is perfectly fine, you only had syntax issues, because you can't initialize an object inline like that. (Hence the unexpected token: .
error)
If you move the object declaration into a separate statement, your code runs correctly without any further modifications:
var q = [ { box: false, name: 'A1', stats: ['average'] },
{ box: false, name: 'A2', stats: ['min', 'max'] } ]
var reduced = _.reduce(q, function(statHash, val) {
var o = {}; o[val.name] = val.stats;
return _.extend(statHash, o);
}, {});
Here's a plunkr with the fixed code. But as it is noted in other answers, undescore is actually not necessary for this task.
Upvotes: 1
Reputation: 106147
Your intuition was correct; reduce
is the right way to go:
var q = [ { box: false, name: 'A1', stats: ['average'] },
{ box: false, name: 'A2', stats: ['min', 'max'] } ];
var result = q.reduce(function(res, obj) {
res[obj.name] = obj.stats;
return res;
}, {});
console.log(result);
// => { A1: ["average"], A2: ["min", "max"] }
Remember that reduce
is standard in all modern browsers, so you don't need Underscore.js for it unless you're stuck supporting IE8. If you have to support IE8, it's identical in Underscore except that you'll call _.reduce(q, function...
instead of q.reduce(function...
.
Upvotes: 2
Reputation: 61275
try this...
var q = [ { box: false, name: 'A1', stats: ['average'] },
{ box: false, name: 'A2', stats: ['min', 'max'] } ]
var testObj = {};
for (var i = 0; i < q.length; i++) {
testObj[q[i].name] = q[i].stats;
}
Upvotes: 2