gpt4 book ai didi

javascript - 将 json 转换为嵌套的 JavaScript 对象

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

我有一个 json int 文件,其中包含如下任何项目:

输入JSON

{
"action.button.submit": "Submit"
"action.button.submitting": "Submitting"
"buttons.common.add": "Add"
"buttons.common.reset": "Reset"
"constants.bom.conditional.or.mandatory.conditional": "Conditional"
"constants.bom.conditional.or.mandatory.mandatory": "Mandatory"
}

输出

{
action: {
button: {
submit: 'Submit'
submitting: 'Submitting'
}
},
buttons: {
common: {
add: 'Add',
reset: 'Reset'
}
},
constants: {
bom: {
conditional: {
or: {
mandatory:{
conditional: 'Conditional',
mandatory: 'Mandatory'
}
}
}
}
}
}

这是我所能得到的:

newData = {};
Object.keys(data).forEach(item => {
const splitData = item.split('.');
splitData.forEach((detail, index) => {
if(index === 0 && !newData[detail]) newData[detail] = {};
})
});
console.info(newData)

我想采用Input并使其看起来像output

最佳答案

您必须递归深入遍历结果对象:

function parse(obj) {
const root = {};

for(const [key, value] of Object.entries(obj)) {
const parts = key.split(".");
const parent = parts.slice(0, -1).reduce((acc, part) => acc[part] || (acc[part] = {}), root);
parent[parts.pop()] = value;
}

return root;
}

关于javascript - 将 json 转换为嵌套的 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54710920/

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