Underscore.js - Map Array of key/value pairs to an Object - One liner

爷,独闯天下 提交于 2019-12-20 10:21:47

问题


I've been going through the underscore docs but I can't seem to find a method (or nested method call) to do the following transformation:

Let's say I have the following Javascript array:

 [{ "name" : "sEcho", "value" : 1},{ "name" : "iColumns", "value" : 12}, ... ]

And I need to transform it into the following object:

 {
      sEcho: 1,
      iColumns: 12,
      ...
 }

I'm using underscore.js for a reason so it must be a one liner.


回答1:


Since nobody has posted this as an answer, I'm posting it because I think it is better than Jan's answer. It's shorter, and cleaner without the inline function.

_.object(_.pluck(data, 'name'), _.pluck(data, 'value'));



回答2:


Variation on Sza's answer, using the "array of pairs" signature of _.object:

_.object(_.map(data, function(x){return [x.name, x.value]}))



回答3:


This should do it:

_.reduce(array, function(o, v){
    o[v.name] = v.value;
    return o;
}, {});

As a one-liner (you are kidding me, right?):

_.reduce(array,function(a,b){a[b.name]=b.value;return a},{});



回答4:


var names = _.pluck(data, 'name');
var values = _.pluck(data, 'value');
var result = _.object(_.zip(names, values));
console.log(result);



回答5:


Let's say you have the following JavaScript array:

var list = [
    {
         name: "sEcho",
         value: 1
    },
    {
         name: "iColumns",
         value: 12
    },
    ...
];

You can convert it into the format you want as follows:

var table = _.reduce(list, function (table, item) {
    table[item.name] = item.value;
    return table;
}, {});

It's not a one liner, but I don't think you literally meant a one liner. Did you?

Here's a one liner if you really meant a one liner:

var t = _.reduce(list, function (t, i) { return t[i.name] = i.value, t; }, {});

Yes, others have provided the same answer. However that's only because the answer to your question is so simple.




回答6:


var a =  [{ "name" : "sEcho", "value" : 1},{ "name" : "iColumns", "value" : 12} ];

var o = {}; _.each(a, function(e) { o[e.name] = e.value; });

console.log(o);
// Object {sEcho: 1, iColumns: 12} 



回答7:


perfect place to use reduce I think:

_.reduce(ary, function(memo, obj){ memo[obj["name"]] = obj["value"]; return memo }, {});




回答8:


var arr = [{ "name" : "sEcho", "value" : 1},{ "name" : "iColumns", "value" : 12}]

ES6

_.mapObject( _.indexBy(arr, 'name'), (v) => v.value )

ES5

_.mapObject( _.indexBy(arr, 'name'), function (v) { return v.value; } )

This iterates twice though



来源:https://stackoverflow.com/questions/17802140/underscore-js-map-array-of-key-value-pairs-to-an-object-one-liner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!