TJR
TJR

Reputation: 6577

Javascript create Object by array

I try to create an object with a value for the last key. I just have an Array with the keys and the value but dont know how it will be possible to create an object without use references in javascript.

As far as I know there isnt a way to create a reference of a variable 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 the best way in JavaScript ?

Upvotes: 1

Views: 187

Answers (4)

adhil muhammed
adhil muhammed

Reputation: 35

If you want the output like

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

Do the following

var keys = ['this', 'is', 'a', 'test'];
var output = keys.reduceRight((p,c)=>({[c]:p}))
console.log(output)

And the output will be like

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

Upvotes: 0

Phil
Phil

Reputation: 164793

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're not a fan of object literal key 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.

Upvotes: 10

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

With this:

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'
       }
     }
   }
}

As opposed to the other answers, this outputs exactly what you asked for.

Cheers

Upvotes: 4

Phrogz
Phrogz

Reputation: 303253

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

Upvotes: 2

Related Questions