前提
空のオブジェクトに object.foo.bar
とか object.hoge.fuga.moge
とか階層が不特定で値を入れたいみたいな
コード
const payload = {path: 'come.on.baby.america', value: 'U.S.A'} const segments = payload.path.split('.') let object = {} let segment_path = '' segments.forEach((segment) => { let i = 0 segment_path = [segment_path, segment].join('.') eval(`object${segment_path} = ${segments.length < i ? payload.value : '{}'}`) i++ }) eval(`object${segment_path} = '${payload.value}'`) console.info(JSON.stringify(object)); //-> {"come":{"on":{"baby":{"america":"U.S.A"}}}}
こんな感じ?