javascript - How can I create a nested object from a list of keys and a value? -


i trying come script take array of keys , 1 value , return object:

keys = ['a', 'b', 'c']; value = 'hello'; 

and trying this:

{'a': {'b': {'c': 'hello'}}} 

my code:

var data = {}; (var i=0; < keys.length; i++) {   var key = keys[i];   if (i < keys.length -1) {      if (data[key] === undefined) {        data[key] = {};     }   } else {     data[key] = value;   }   data = data[key]; } 

also want make sure data contained in data value not erase whenever uses different key.

you can use array.prototype.reduceright, this

var keys = ['a', 'b', 'c']; var value = 'hello';  console.log(keys.reduceright(function (pastresult, currentkey) {     var obj = {};     obj[currentkey] = pastresult;     return obj; }, value)); // { a: { b: { c: 'hello' } } } 

reduceright process array right left. , everytime create new object , store old object against current key name. so, iterate 1 one, increasing nesting of objects. pass value last parameter, used pastresult first time.


if want fix original code, have stop assigning new objects data , use variable, this

var keys = ['a', 'b', 'c'],     value = 'hello',     data = {},     temp = data;  (var = 0; < keys.length; i++) {     var key = keys[i];     if (i < keys.length - 1) {         if (temp[key] === undefined) {             temp[key] = {};         }     } else {         temp[key] = value;     }     temp = temp[key]; }  console.log(data) // { a: { b: { c: 'hello' } } } 

even can written succinctly, this

for (var = 0; < keys.length - 1; i++) {     temp = (temp[keys[i]] = {}); } temp[keys[keys.length - 1]] = value; 

we iterate keys except last 1 , assign new object current key every time , since assign temp, on next iteration temp refer newly created object. , finally, assign value last element of keys.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -