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

161
Visualizações
Creating a nested object from array of keys and target values

I have and array of objects which I would like to transform into single js object. The array contains target value and array of keys. Note: I want this to work in vanilla js without importing scripts.

The source array:

[ 
  { value: 'res-1', keys: [ 'first' ] },
  { value: 'res-2', keys: [ 'second', 'deeperOne' ] },
  { value: 'res-3', keys: [ 'second', 'deeperTwo' ] },
  { value: 'res-4', keys: [ 'second', 'deeperThree', 'moreDeeper' ] },
  { value: 'res-5', keys: [ 'third' ]} 
 ]

Desirable result (object):

{
  first: 'res-1',
  second: {
    deeperOne: 'res-2',
    deeperTwo: 'res-3',
    deeperThree: {
      moreDeeper: 'res-4'
    }
  },
  third: 'res-5'
}

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

cmgchess gave answer to the question with a comment. Here is the code!

const array = [ 
  { value: 'res-1', keys: [ 'first' ] },
  { value: 'res-2', keys: [ 'second', 'deeperOne' ] },
  { value: 'res-3', keys: [ 'second', 'deeperTwo' ] },
  { value: 'res-4', keys: [ 'second', 'deeperThree', 'moreDeeper' ] },
  { value: 'res-5', keys: [ 'third' ]} 
 ]

const set = (obj, path, value) => {
  path.reduce((acc, key, i) => {
    if (acc[key] === undefined) acc[key] = {}
    if (i === path.length - 1) acc[key] = value
    return acc[key]
  }, obj)
}

let object = {}
array.forEach(({value, keys}) => set(object, keys, value))

console.log(object)

about 4 years ago · Santiago Trujillo 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