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

152
Visualizações
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 Respostas
Responde à pergunta

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 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