1

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 ?

5
  • JSON? Commented Jan 8, 2014 at 5:18
  • I dont think that JSON can help me with this. I have an Array with Keys. Every key have to be a new object in the object. And the last key has the value of the variable "value". Commented Jan 8, 2014 at 5:20
  • 1
    Are you sure that inner value isn't meant to be test: 'Test'? Commented Jan 8, 2014 at 5:31
  • @Phil yes - for sure. My fault. I will edit the question. But thanks to your awesome answer (: It still works how it has to work. Commented Jan 8, 2014 at 5:47
  • I edited to a salomonic data, so no previously correct answer gets incorrect :) Commented Jan 8, 2014 at 5:55

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It has an error in the final node, but this code is so beautiful I can't downvote it
It finally creates test: "Test" instead of Test : "test". But anyway, altough it's not correct it has my vote, nice code
@EdgarVillegasAlvarado Ah. The OP's description makes it sound like the value should be the inner-most value, not key. I've asked for clarification
Wow. Awesome. Never heard about this method in javascript before. Thanks for this clean code. I will try it and will work with this. Edit: I tried it and this works fine for my issue! Many thanks dude :)
4

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

6 Comments

Did you get that terseness from my answer, or on your own? (s'ok either way)
I was refactoring each minute (you can see the editions), didn't even realize you answered. Mine gives a different result, though
Yes, yours gives the answer the OP asks for (which I suspect is wrong :)
Anyhow, note that the value of i after the loop will be the value of keys.length-1, so you can use that to make your last line cleaner, if you like.
Don't look now but OP updated their question ;). Still gets my upvote for the effort of figuring out how to solve the more difficult original query
|
2
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"}}}}

2 Comments

keys was already an array? Why turn it into a string then back to an array?
@Phil BC I was too lazy to use the mouse to copy/paste, and I wanted to show the OP an alternate lazy-programmer way to create an array of strings with less typing.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.