Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

Try this:

stringOptionsOutlet.map((v) => ({ ...v, value: v.id }));
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda