gpt4 book ai didi

Javascript,如何用点分割键来恢复json结构

转载 作者:行者123 更新时间:2023-11-30 08:29:41 25 4
gpt4 key购买 nike

我有一个json,它是

{ 
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
}

我想恢复结构,比如

{ 
"prop1": {
"sub1": {
"sub2" : "content1",
"sub3" : "content2"
}
},
"prop2": {
"sub1": {
"sub2" : "content3"
}
},
"prop3": {
"sub1": {
"sub2" : "content4"
}
}
}

我用点分割键来得到每个键。

for (var key in json) {
var keySplit = key.split('.');
// Todo: recovery the structure
}

但没有找到好的解决方案。

有人有解决办法吗?

最佳答案

您可以使用 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);

关于Javascript,如何用点分割键来恢复json结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39865991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com