Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
How to convert array of array of strings into an object where each string is the key of an object that includes the next

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda