[英]Convert json into nested JavaScript Object
我有一個json int
文件,其中包含以下任何項目:
{
"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
您可以在對象條目上使用一個forEach
循環,然后在上拆分每個鍵.
。 之后,您可以在該鍵數組上使用reduce
方法來構建嵌套對象。
const obj = { "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" } const res = {} Object.entries(obj).forEach(([key, value]) => { key.split('.').reduce((r, e, i, a) => { return r[e] || (r[e] = (a[i + 1] ? {} : value)) }, res) }) console.log(res)
使用Lodash,您可以通過_.set
方法執行此操作, _.set
方法采用目標對象,嵌套鍵和值。
const obj = {"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"} const res = {} _.forEach(_.entries(obj), ([k, v]) => _.set(res, k, v)) console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
您必須遞歸地遍歷結果對象:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.