Home > Software design >  each value of array is a object subproperty of the previous array value
each value of array is a object subproperty of the previous array value

Time:06-06

so I have an array ['banana', 'apple', 'grape']

how can I transform into the object below?

{
   banana: {
       apple: {
           grape: { }
       }
   }
}

CodePudding user response:

You can use reduceRight() to recursively build the result object:

const data = ['banana', 'apple', 'grape'];

const result = data.reduceRight((a, v) => ({ [v]: a }), {});

console.log(result);

CodePudding user response:

You can simply loop over given value and keep track of previously added object

let arr = ['banana', 'apple', 'grape']


function createObj(arr) {
  let obj = {}
  let temp = obj

  for (let key of arr) {
    temp[key] = {}
    temp = temp[key]
  }
  return obj
}

console.log(createObj(arr))

  • Related