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

147
Vistas
JavaScript - Object creating with reduce method and ({}) meaning

I have been learning JS for few months now, and everything is going good, but sometimes I encounter things I do not understand or I did miss them. So, I was doing some Object oriented exercises and my assignment was to convert some values into numbers. I wasn't sure how to do it, and after some researching I came up with this function:

function convertToNumber(obj) {
  return Object.entries(obj).reduce((acc, [k, v]) => ({ ...acc, [k]: +v }), {});
}

Things I do not understand are:

  1. Why do we need to use({ }) and not only{}? I guess it have something to do with object concatenation, but would like to be sure.
  2. Why do I need to put key in[ ] brackets? Is it because at first I used spread operator on object? Is it like writing acc[k] in some sense?

Thank you in advance

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

- Why do we need to use ({ }) and not only {}? I guess it has something to do with object concatenation but would like to be sure.

This is used to directly return an object in the arrow function to distinguish it from the parenthesis used to wrap the function body. The two are the same:

(acc, [k, v]) => ({ ...acc, [k]: +v })
(acc, [k, v]) => { return { ...acc, [k]: +v }; }

- Why do I need to put the key in [ ] brackets? Is it because at first, I used the spread operator on the object? Is it like writing acc[k] in some sense?

The brackets are mainly used to set the key as the dynamic value of k. Here is a simple example:

const x = 'id';
console.log({ x: 1 });
console.log({ [x]: 1 });

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