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

How can I convert something like an initialArray of JSON objects to a 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' } 

What to consider:

Any ideas?

+4
source share
8 answers

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

You should also use a regular loop to iterate over the 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) );​ 
+3
source

Demo

You can loop through the array and add a new property to finalObject for each object, whose property name is an identifier 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; 
+2
source

resp[key.id] = key.img;

You will correctly name him. But you need meaning;

resp[x[key].id] = x[key].img;

+1
source
 var finalObject = initialArray.reduce(function(ret, obj){ ret[obj.id] = obj.name; return ret; }, {}); 

This solution relates to property names for a specific question, but Array.prototype.reduce is a function that I use all the time for any iteration of any type that requires a result without an array.

+1
source

You are not using For In correctly jsFiddle

 var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ]; var resp = {}; for( var key in x ){ resp['id' + x[key].id] = x[key].img; } document.write( JSON.stringify(resp, undefined, 2) ); 

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

If I understood correctly, you can do something like

 var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]'; var resp = {}; var json = $.parseJSON(x); $(json).each(function(i,v){ resp[v.id]=v.img; }); console.log( resp); 

Demo

you were talking about json, but there was no json in the script you provided, even jquery was not added as a resource, so I made some assumptions

0
source

Today I had the same question, and I did not find an answer here, except for the answer @ adam-rackis.

I found:

 var initialArray = [ { id:'id1', name:'name1' }, { id:'id2', name:'name2' }, { id:'id3', name:'name3' }, { id:'id4', name:'name4' } ], finalObject = {}; $.each(initialArray, function(k,v) { finalObject[v.name] = v.value; }); 
0
source

Source: https://habr.com/ru/post/1399466/


All Articles