FarazShuja
FarazShuja

Reputation: 2370

Creating objects from array to json object

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"},
}

Upvotes: 0

Views: 62

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382102

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

Upvotes: 6

Related Questions