简体   繁体   中英

Transforming this array into an object with underscore

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?

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

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... .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM