我试图建立一个嵌套对象,我会尽量让自己清楚。
我有这个 json 结构:
{
"origin.geo.country": "USA",
"origin.geo.state": "NY",
"origin.geo.zip": 4444,
"user.name": "Michael",
"user.surname": "Jordan"
}
我需要一个输出如下内容的函数:
{
origin: {
geo: {
country: "USA",
state: "NY",
zip: 4444
}
},
user: {
name: "Michael",
surname: "Jordan"
}
}
我知道我必须使用递归来实现这一点,但我无法对其进行编码。你们能帮我解决这个问题吗?
谢谢。
所以伙计们,
@Ben Beck 的回答帮助了我。
我只需要对函数做一些小的改动:
function (path,value,obj) {
var parts = path.split("."), part;
//reference the parent object
var parent = obj;
while(part = parts.shift()) {
// here I check if the property already exists
if( !obj.hasOwnProperty(part) ) obj[part] = {};
// if is the last index i set the prop value
if(parts.length === 0) obj[part] = value;
obj = obj[part]; // update "pointer"
}
//finally return the populated object
return parent;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句