Create a dynamic nested object from array of properties

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

    You can use the following Function

    function arr2nestedObject(myArray){
     var cp_myArray = myArray;
     var lastobj = {};
     while(cp_myArray.length>0){
        newobj = {};
        var prop = cp_myArray.pop();
        newobj[prop] = lastobj;
        lastobj = newobj;
     }
     return lastobj;
    }
    

    The following code:

    var myArray = ["personal-information", "address", "street",'Great-Success'];
    console.log(JSON.stringify(arr2nestedObject(myArray),undefined,2));
    

    Would Produce the Following Output:

    {
      "personal-information": {
       "address": {
        "street": {
         "Great-Success": {}
         }
        }
      }
    }
    
    Please let me know if that was what you meant.

    Kind Regards.

提交回复
热议问题