将json转换为嵌套的JavaScript对象

时间:2019-02-15 13:59:43

标签: javascript json

我有一个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

2 个答案:

答案 0 :(得分:1)

您可以在对象条目上使用一个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方法执行此操作,该方法采用目标对象,嵌套键和值。

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>

答案 1 :(得分:1)

您必须递归地遍历生成的对象:

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;
}