2 个回答
var prop2obj = prop => Object.keys(prop).reduce((res,key) => {
    key.split('.').reduce((obj, k, i, arr) => obj[k] = i == arr.length-1 ? prop[key] : (obj[k] || {}), res);
    return res;
}, {});

prop2obj({

'a.b.c': 1,

'a.d': 2,

'e' : 3

})
function makeObj (input = {}) {
    const output = {};

    for (const [path, value] of Object.entries(input)) {
        let target = output;
        let key = "";
        for (const char of path) {
            switch (char) {
            case ".":
                target = target[key] ?? (target[key] = {});
                key = "";
                break;
            default:
                key += char;
            }
        }
        target[key] = value;
    }

    return output;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏