Create a dynamic nested object from array of properties

后端 未结 5 1719
醉酒成梦
醉酒成梦 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

    As @p.s.w.g answer is a very good answer with pure js, but if you want an alternative with in a descriptive and functional way of that and set a value for final nested prop, you can use ramdajs assocPath https://ramdajs.com/docs/#assocPath like below:

    var array = ['opt1','sub1','subsub1','subsubsub1'];
    
    R.assocPath(array, "the value", {}); 
    

    more details:

    Makes a shallow clone of an object, setting or overriding the nodes required to create the given path, and placing the specific value at the tail end of that path. Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.

    examples:

    R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}
    
    // Any missing or non-object keys in path will be overridden
    R.assocPath(['a', 'b', 'c'], 42, {a: 5}); //=> {a: {b: {c: 42}}}
    

提交回复
热议问题