I have an array of object like this
[
{"id": "1", "name": "test"},
{"id": "2", "name": "test2"},
{"id": "3", "name": "test3"}
]
I want to convert it to object list this
{
"1": {"name": "test"},
"2": {"name": "test2"},
"3": {"name": "test3"},
}
asked Apr 29, 2014 at 10:44
FarazShuja
2,3802 gold badges23 silver badges34 bronze badges
-
5"Creating objects from array to json object" sigh It's not a "json object." It's just an object. JSON is a textual notation for data interchange.T.J. Crowder– T.J. Crowder2014年04月29日 10:47:35 +00:00Commented Apr 29, 2014 at 10:47
-
Why in first place didn't you generate an object instead of an array of objects? Maybe this array comes from any third party script but i have to ask it.A. Wolff– A. Wolff2014年04月29日 10:57:15 +00:00Commented Apr 29, 2014 at 10:57
1 Answer 1
You may use reduce :
var obj = arr.reduce(function(m,o){ m[o.id]={name:o.name}; return m }, {});
Side note : please be sure to read and try to understand T.J.'s comment about JSON
answered Apr 29, 2014 at 10:45
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
T.J. Crowder
@ OP - Note that
Array#reduce requires a modern browser or a shim; if you need to support older browsers like IE8, search for "es5 shim" for options.Denys Séguret
@T.J.Crowder You're right but isn't it time we stop telling that ? After all even gmail stopped supporting IE9 long ago (this is a question, not a critic of the comment).
T.J. Crowder
@ dystroy: My take is that when 6% to 21% of people globally are still using a browser (IE8), it's still relevant and important. Despite the XP deadline having passed, I suspect we're stuck with IE8 a while longer. I can't afford for even 6% of my users to have my site fail with a random script error. And the note is easy to add. Now of course, the only stats that really matter are the stats for one's own site...
lang-js