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

116
Visualizações
How to Convert Nested Object in Key Value Pair in Javascript

I want to do this with programming

Problem

  attributes: {
    allow: [ '0' ],
    create: [ '0' ],
    all: [ '0' ],
    rfid: [ '0' ],
}

What I want is

  attributes: {
    allow:'0',
    create: '0',
    all:'0',
    rfid: '0',
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Functional approach:

You can use Object.entries to turn an object { a: 1, b: 2 } into an array of arrays (containing pairs of keys and values) [['a', 1], ['b', 2]]. You can then use Array#map to apply an operation on each and mapping each element of the array to the return value of the operation. In our case, we'll actually have something like [['allow', ['0']], ...] at that point and want to map it to [['allow', '0'], ...]. Then at the end, we undo the first operation using Object.fromEntries to get an object back.

The mapping operation can be simply ([k, [v]]) => [k, v]. Using destructuring, we get an expressive way of extracting the value that we need and returning it.

Now since the whole thing seems to be inside another object with attributes as key (and I don't know if there can be other keys), we'll return another such object with attributes replaced and the other keys preserved:

function transform (object) {
  return {
    ...object,
    attributes: Object.fromEntries(
      Object.entries(object.attributes).map(([k, [v]]) => [k, v])
    )
  }
}

Imperative approach:

This approach is simpler, but will mutate your object. You can loop over the keys in the attributes object and replace each value with its own first array element, as follows:

function transform (object) {
  for (const key in object.attributes) {
    object.attributes[key] = object.attributes[key][0]
  }
  
  return object
}
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