javascriptarraysalgorithmobjectcreation

How does one incrementally build a nested object structure from an array of property names?


My task is straight forward. I have an array of strings:

let a=["a","b","c"];

And i want to convert that array to (can alter the original array, doesn't matter) what i would like to call as "recursive object" just so:

//in json format just to demonstrate
"object": {
    "a": {
      "b":{
        "c":{
          
        }
        
      }
    }
  }

I've tried the following logic but couldn't get it to work due to reference problem and i couldn't build recursion.

let tempObj;
let obj2;

array.slice().reverse().forEach(function(item,index){
    
        obj2=tempObj;
        tempObj[item]="";
      
    });

Just to make sure we are on the same page, another example:

let arr=["alpha","beta","gamma"];
let magicObj=someMagicFunction(arr);
//magicObj["alpha"]["beta"]["gamma"] contains the value ""

Thanks


Solution

  • Here is a simple solution:

    const arr = ["a","b","c"];
    const result = arr.reverse().reduce((obj, key) => ({[key]: obj}), {})
    console.log(result)

    Here a little explaination:
    o is the result of the last iteration and v is the current element in the array. {[v]: o} creates a new object and sets the property v to o and returns that.