Create a dynamic nested object from array of properties

后端 未结 5 1706
醉酒成梦
醉酒成梦 2020-12-03 03:20

This sounds like a simple task, but I can\'t quite figure it out: I have an array :

var array = [\'opt1\',\'sub1\',\'subsub1\',\'subsubsub1\']
5条回答
  •  伪装坚强ぢ
    2020-12-03 03:57

    You can use reduceRight to transform the array into a 'chain' of objects:

    const array = ['a', 'b', 'c'];
    const object = array.reduceRight((obj, next) => ({[next]: obj}), {});
    
    // Example:
    console.log(object); // {"a":{"b":{"c":{}}}}

提交回复
热议问题