0

I am passing a dot separated string into function

console.log( namespace('a.b.c.d.e'))

and expect get next result

//result => "{"a":{"b":{"c":{"d":{"e":{}}}}}}"

my try (I don't know how to do it recursively)

const namespace = (string)=> {
  return string.split('.').reduce((acc,el)=>{
    acc[el] = {}
  },{})
}
alex
  • 137
  • 1
  • 8

2 Answers2

1

How about the below iteration approach :-

function namespace(input){
let result = {};
let temp = result;
const inputArr = input.split(".");
inputArr.forEach((ele)=>{
  temp[ele] = {};
  temp = temp[ele];
})
return result;
}

console.log( namespace('a.b.c.d.e'))
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
1

const input = "a.b.c.d.e"

const output = input.split('.').reverse().reduce((acc,el)=>{
  return {[el]: acc}
},{})
  
console.log(output)
Nghi Nguyen
  • 910
  • 6
  • 10