如何将点表示法中的字符串转换为具有值的嵌套对象?
How do I turn a string in dot notation into a nested object with a value?
我试图用 split 和 reduce 来做到这一点,但我想不通。
这是我的字符串和值
const str = "stack.overflow.is.cool"
const value = "Indeed"
我想把它变成
{ stack:
{ overflow:
{ is:
{ cool: indeed }
}
}
}
有地图。也可以使用 reduce 和递归函数..
const str = "stack.overflow.is.cool"
const value = "Indeed"
let obj = {};
let pointer = obj;
str.split('.').map( (key, index, arr) => {
pointer = (pointer[key] = (index == arr.length - 1? value: {}))
});
console.log(JSON.stringify(obj, null, ' '));
我试图用 split 和 reduce 来做到这一点,但我想不通。
这是我的字符串和值
const str = "stack.overflow.is.cool"
const value = "Indeed"
我想把它变成
{ stack:
{ overflow:
{ is:
{ cool: indeed }
}
}
}
有地图。也可以使用 reduce 和递归函数..
const str = "stack.overflow.is.cool"
const value = "Indeed"
let obj = {};
let pointer = obj;
str.split('.').map( (key, index, arr) => {
pointer = (pointer[key] = (index == arr.length - 1? value: {}))
});
console.log(JSON.stringify(obj, null, ' '));