2

Could someone help me to create a JavaScript function that would turn the string below into an Object?

var structure = 'user.location.city';

When ran through the JavaScript function would return an object structured like this:

user: {
  location: {
    city: {}
  }
}

I came up with the code below, but the object is messed up:

var path = structure.split('.');
var tmp_obj = {};
for ( var x = 1; x < path.length; x++ ) {
   tmp_obj[path[x]] = {};
};

I don't know how to add the "city" Object to the "location" Object.

1

1 Answer 1

3
var path = structure.split('.');
var tmp_obj = {};
var obj = tmp_obj;
for(var x = 1; x < path.length; x++) {
    tmp_obj[path[x]] = {};
    tmp_obj = tmp_obj[path[x]];
};
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work for me. plnkr.co/edit/VjFiOGl2AC83HcLGQTJv?p=preview You are not using the "obj" variable? Why don't you count from 0 instead of 1?
An alternative answer can be found here: stackoverflow.com/questions/32029546/…

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.