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


Students in first year.. 😂 | #shorts #jennyslectures #jayantikhatrilamba

Bro’s hacking life 😭🤣

BEST DEFENCE ACADEMY IN DEHRADUN | NDA FOUNDATION COURSE AFTER 10TH | NDA COACHING #shorts #nda #ssb

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



Views -