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
  • 12,096
  • 4
  • 53
  • 70

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
  • 310,957
  • 84
  • 592
  • 636
  • 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? – ESP32 Jul 28 '16 at 09:42
  • An alternative answer can be found here: http://stackoverflow.com/questions/32029546/create-a-javascript-object-from-string – ESP32 Jul 28 '16 at 09:56