JavaScript function to create a structured object from a string?

Can someone help me create a JavaScript function that turns the line below into an object?

var structure = 'user.location.city';

When the JavaScript function was launched, an object was structured as follows:

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 do not know how to add a city object to a location object.

+2
source share
1 answer
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]];
};
+3
source

All Articles