JavaScript函数从字符串创建结构化对象? [英] JavaScript function to create a structured Object from a String?

查看:89
本文介绍了JavaScript函数从字符串创建结构化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我创建一个JavaScript函数,将下面的字符串变成一个Object吗?

  var structure =' user.location.city; 

运行JavaScript函数时,会返回一个像这样的对象:

 用户:{
位置:{
city:{}
}
}

我想出了下面的代码,但是这个对象很乱:

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

我不知道如何将城市对象添加到位置对象。 / p>

解决方案

  var path = structure.split('。'); 
var tmp_obj = {};
var obj = tmp_obj;
for(var x = 1; x tmp_obj [path [x]] = {};
tmp_obj = tmp_obj [path [x]];
};


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.

解决方案

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]];
};

这篇关于JavaScript函数从字符串创建结构化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆