Pea*_*Pan 1 javascript json split
我有一个json,它是
{
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
}
Run Code Online (Sandbox Code Playgroud)
我想恢复结构,比如
{
"prop1": {
"sub1": {
"sub2" : "content1",
"sub3" : "content2"
}
},
"prop2": {
"sub1": {
"sub2" : "content3"
}
},
"prop3": {
"sub1": {
"sub2" : "content4"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我用点分开键来获得每个键.
for (var key in json) {
var keySplit = key.split('.');
// Todo: recovery the structure
}
Run Code Online (Sandbox Code Playgroud)
但没有找到一个好的解决方案.
有人有解决方案吗?
你可以使用Array#reduce方法.
var obj = {
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
};
// iterate over the property names
Object.keys(obj).forEach(function(k) {
// slip the property value based on `.`
var prop = k.split('.');
// get the last value fom array
var last = prop.pop();
// iterate over the remaining array value
// and define the object if not already defined
prop.reduce(function(o, key) {
// define the object if not defined and return
return o[key] = o[key] || {};
// set initial value as object
// and set the property value
}, obj)[last] = obj[k];
// delete the original property from object
delete obj[k];
});
console.log(obj);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
562 次 |
| 最近记录: |