ARTICLEViews: 19Share  Posted by - Anonymous

interview question - function to convert given string to object a.b.c = "test"

function to convert given string to object

input: 

a.b.c = "test"


output: 

{ a : { b : { c : "test" } } }


Solution:



function getObj(key, value){

 const rtnObj = {};

  

 const subKeys = key.split(".");


 const getNestedKey = (obj, nextKey, value) => {

  obj[nextKey] = value;

 }


 if(subKeys.length){

  let currObj = rtnObj;

  for(let i =0; i < subKeys.length; i++){ // 0 , 1 , 2

    

   if(i + 1 === subKeys.length){  

    console.log("last key", subKeys[i]);

    currObj[subKeys[i]] = value;

   }

   else {

    currObj[subKeys[i]] = {};

   }

   currObj = currObj[subKeys[i]];

  }


 }


 return rtnObj;

}


console.log(getObj("a.b.c", "test"));



Views -