How to convert array of array of strings into an object where each string is the key of an object that includes the next

Viewed 41

I have an array formatted like so

const array = [
  ['technology', 'apple', 'computers', 'macbook_pro'],
  ['technology', 'apple', 'computers', 'macbook_air'],
  ['technology', 'apple', 'phones', 'iphone'],
  ['technology', 'samsung', 'phones', 'Galaxy S21'],
]

And I need to convert it to an object formatted like so:

{
  technology: {
    apple: {
      computers: {
        macbook_pro: {},
        macbook_air: {}
      },
      phones: {
        iphone: {}
      }
    },
    samsung: {
      phones: {
        galaxy_s21: {}
      }
    }
  }
}

I tried getting it done with a two forEach loops but I keep getting stuck.

2 Answers

Using Array#reduce, iterate over the array while updating an object accumulator.

In every iteration, set a current to the accumulator and iterate over the current list using Array#forEach. If current doesn't have a property, set the value to {} using the nullish operator. Then, reset current to it to be used in the next iteration.

const array = [
  ['technology', 'apple', 'computers', 'macbook_pro'],
  ['technology', 'apple', 'computers', 'macbook_air'],
  ['technology', 'apple', 'phones', 'iphone'],
  ['technology', 'samsung', 'phones', 'Galaxy S21'],
];

const res = array.reduce((acc, props) => {
  let current = acc;
  props.forEach(prop => {
    current[prop] ??= {};
    current = current[prop];
  });
  return acc;
}, {});

console.log(res);

Array.reduce implementation is added below

  • Loop through the input array
  • Loop through each node in the input array.
  • Check if accumulator has the node with that key.
  • If no create an empty object as that node in accumulator.
  • Keep the newly created node or existing node as temp value.
  • This temp variable keeps on drilling your accumulator object inside the loop.

const array = [
  ['technology', 'apple', 'computers', 'macbook_pro'],
  ['technology', 'apple', 'computers', 'macbook_air'],
  ['technology', 'apple', 'phones', 'iphone'],
  ['technology', 'samsung', 'phones', 'Galaxy S21'],
]
const output = array.reduce((acc, curr) => {
  let temp = acc;
  curr.forEach((node) => {
    if (!temp[node]) {
      temp[node] = {}
    }
    temp = temp[node]
  })
  return acc;
}, {});
console.log(output)

Related