Javascript creates an object by array

I am trying to create an object with a value for the last key. I just have an Array with keys and value, but I don’t know how to create an object without using links in javascript.

As far as I know, there is no way to create a variable reference in javascript.

This is what I have:

var value = 'test'; var keys = ['this', 'is', 'a', 'test']; 

This is what I want:

 myObject: { this : { is: { a : { test : 'test' } } } } 

Any idea how I can do this in the best way in JavaScript?

+1
source share
3 answers

How about this ...

 const value = 'test' const keys = ['this', 'is', 'a', 'test'] const myObject = keys.reduceRight((p, c) => ({ [c]: p }), value) console.info(myObject) 

Or, if you are not a fan of object shortcuts and arrow functions ...

 keys.reduceRight(function(p, c) { var o = {}; o[c] = p; return o; }, value); 

See Array.prototype.reduceRight () - Polyfill if you need IE <= 8 support.

+8
source

Wherein:

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

Outputs:

 { this : { is: { a : { Test : 'test' } } } } 

Unlike other answers, this prints out exactly what you requested.

Greetings

+4
source
 var o={}, c=o; var value = 'Test'; var keys = 'this is a test'.split(' '); for (var i=0; i<keys.length-1; ++i) c = c[keys[i]] = {}; c[keys[i]] = value; console.log(JSON.stringify(o)); // {"this":{"is":{"a":{"test":"Test"}}}} 
+1
source

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


All Articles