Search code examples
javascriptobjectprototypejs

Push one object property with the same object in javascript


I have to frame object structure like below dynamically.

   "1":{
    "A":"one.two.three" 
    },
    "2":{
    "B":"three.four.five" 
    },
    "3":{
    "c":"six.seven.eight"
    }, 
    etc....

    Obj ={
    A: "123",
    B: "345",
    C :"678"
    }

EXPECTED OUTPUT SHOULD BE AS BELOW

  "Parent" :{
     "one":{
       "two"{
          "three" :"123" (from Obj A)
         }
       }
     "three": {
       "four":{
         "five" :"345" (from Obj B)
         }
      }
     etc...`
`   }

so i have tried the below approach. But it does not work.

Var temp = {}
temp["one"] ="1";
temp["two"] = temp; (and) temp["one"]
temp["three"] = temp; (and) temp["two"]

Solution

  • var t={};
    var temp=t;
    for(var i=3 ; i>0 ;i--){
       if(i!=1)t[i]={};
       else t[i]=i; 
       t=t[i];
    }
    JSON.stringify(temp);
    

    Output is : "{"3":{"2":{"1":1}}}"