Javascript,如何用dot拆分键来恢复json结构

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)

但没有找到一个好的解决方案.

有人有解决方案吗?

Pra*_*lan 5

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

  • 对于将来任何正在寻找解决方案来处理不带“.”的键的人:只需将所有内容包装在“var prop = k.split('.');”之后的“forEach”中,并使用“if (prop .长度> 1)`。甚至“del”。示例:https://codepen.io/anon/pen/MBwgmM?editors=1012 (2认同)