ARTICLEViews: 18Share  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"));


String Array To String || Integer Array To Integer || Mini Java Interview Questions Series

Aspirants practicing eatingetiquette # SSB #SSBPreparation #NDA #CDS #Defence #DefenceAcademy

xavier memes #memes

Biggest mistake I do while recording| behind the scene | #jennyslectures



Views -