1

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: {}
    }
  }
}
1

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.