给定一个JS字符串:var s = "deep.deeper.deepest"
,如何将其转换为如下对象:deep: {deeper: {deepest: {}}}
答案 0 :(得分:2)
const dottedToObj = (str, orig = {}) => (str.split(".").reduce((obj, key) => obj[key] = {}, orig), orig);
将字符串数组(将原始字符串拆分)减少为对象链。或者功能稍差:
function dottedToObj(str){
const root = {};
var acc = root;
for(const key of str.split(".")){
acc = acc[key] = {};
}
return root;
}
答案 1 :(得分:1)
一个简单的循环应该适用于此,只需移动每个虚线属性,同时向下移动对象中的一个级别:
const s = "deep.deeper.deepest";
function convertToObject(str) {
const result = {};
let inner = result;
for (const key of s.split(".")) {
// Give the object a child with this key
inner[key] = {};
// Set the current object to that child.
inner = inner[key]
}
// Return the original
return result;
}
console.log(convertToObject(s))