David Alsh
David Alsh

Reputation: 7609

How to generate an object with nested keys based on an array of arrays that hold it's key locations?

I have an array which contains arrays which describe the children inside an object as strings.

I am having trouble producing the desired result with the supplied input.

let obj = {}

let arr = [
  ["one", "two", "three", "four"],
  ["one", "two", "three", "four"],
  ["one", "two", "three", "four", "five"],
  ["one", "hi"]
]

console.log(JSON.stringify(obj, null, 4))

Desired output:

let result = {
  one: {
    children: {
      two : {
        children: {
          three: {
            children: {
              four: {
                children: {
                  five: {}
                }
              }
            }
          }
        }
      },
      hi: {}
    }
  }
}

Upvotes: 1

Views: 26

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

One option would be to have a reduce nested inside another reduce, one iterating over the property arrays, and one iterating over each property.

You'll have to make sure you're checking the index of the property against the length of the property array, though, since you don't want to make children objects for the most deeply nested objects.

const arr = [
  ["one", "two", "three", "four"],
  ["one", "two", "three", "four"],
  ["one", "two", "three", "four", "five"],
  ["one", "hi"]
];
const output = arr.reduce((a, propArr) => {
  propArr.reduce((obj, prop, i) => {
    if (!obj[prop]) obj[prop] = {};
    if (!obj[prop].children && i !== propArr.length - 1) obj[prop].children = {};
    return obj[prop].children;
  }, a);
  return a;
}, {});
console.log(output);

Upvotes: 2

Related Questions