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

140
Visualizações
Is there a quicker way to copy a value in a key of data object to a new key in the same data object in javascript?

I'm experimenting with how I can make my code more concise when I have a piece of an array of objects received from an API endpoint. This is the initial variabel:

let stringOptionsOutlet = [];

Then I want to make a new key called "value". This is how I normally do (which I think is okey but I believe there must be some disadvantages in comparison with other techniques you might come up with):

stringOptionsOutlet = [...response.data.outlet]; // 1. this is the data I get from an API endpoint, I copy it with the spread operator
stringOptionsOutlet.map((v) => return { ...v, value: "" }; ); // 2. then I make the same new value in every single data object inside the array stringOptionsOutlet
Object.entries(stringOptionsOutlet).forEach((e) => {
   e[1].value = e[1].id; // 3. copy the value of id to the new key
});

The data before I map the data:

[ 
  {
   label: "A1-1",
   id: "1",
  },
  {
   label: "B2-1",
   id: "4",
  },
]

After the mapping (step number 2 and number 3):

[ 
  {
   label: "A1-1",
   id: "1",
   value: "1",
  },
  {
   label: "B2-1",
   id: "4",
   value: "1"
  },
]

Could you also please explain the benefits and shortcomings of the techniques? Thank you.

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

0

What you're doing will work but there are certainly some unnecessary steps as written. There's no need to copy the API response data into an array and then change the array contents when you can map the API response itself.

// You can do steps 1 2 and 3 all in 1 .map()
const stringOptionsOutlet = response.data.outlet.map(v => {
    return {
        ...v,
        value: v.id
    }
})

The downside of doing it all in 1 way is that if you want to do some more complex logic that single .map call could get very cluttered and maybe it'd be simpler to introduce a separate step, with the caveat that you'd then process the data a second time.

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this:

stringOptionsOutlet.map((v) => ({ ...v, value: v.id }));
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