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.
Let's say you have the following JavaScript array:
You can convert it into the format you want as follows:
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:
Yes, others have provided the same answer. However that's only because the answer to your question is so simple.
Variation on Sza's answer, using the "array of pairs" signature of
_.object
:ES6
ES5
This iterates twice though
perfect place to use reduce I think:
_.reduce(ary, function(memo, obj){ memo[obj["name"]] = obj["value"]; return memo }, {});
This should do it:
As a one-liner (you are kidding me, right?):