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.

Rupesh Yadav
  • 15,096
  • 5
  • 54
  • 71

1 Answers1

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]];
};
ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
  • This doesn't work for me. https://plnkr.co/edit/VjFiOGl2AC83HcLGQTJv?p=preview You are not using the "obj" variable? Why don't you count from 0 instead of 1? – Gerfried Jul 28 '16 at 09:42
  • An alternative answer can be found here: http://stackoverflow.com/questions/32029546/create-a-javascript-object-from-string – Gerfried Jul 28 '16 at 09:56