Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array of objects into a mapped object in JavaScript?

How can I convert something like initialArray array of JSON objects into finalObject map?

var initialArray = [
             { id:'id1', name:'name1' },
             { id:'id2', name:'name2' },
             { id:'id3', name:'name3' },
             { id:'id4', name:'name4' }
          ];

var finalObject = {
                  'id1':'name1',
                  'id2':'name2',
                  'id3':'name3',
                  'id4':'name4'
               }

Things to consider:

  • IDs are strings.
  • I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/

Any ideas?

like image 266
Sherzod Avatar asked Mar 02 '12 21:03

Sherzod


2 Answers

You need to operate on the objects in your array, not strings containing their indexes in the array.

You should also use a regular for loop to iterate over an array.

Your JSFiddle, fixed:

var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};

for( var i = 0 ; i < x.length ; i++ ){
    var obj = x[i];
    resp[obj.id] = obj.img;
}

document.write( JSON.stringify(resp, undefined, 2) );
​
like image 162
Quentin Avatar answered Nov 01 '22 07:11

Quentin


DEMO

You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.

var finalObject = {};

for (var i = 0, max = initialArray.length; i < max; i++)
    finalObject[initialArray[i].id] = initialArray[i].name;
like image 20
Adam Rackis Avatar answered Nov 01 '22 09:11

Adam Rackis