Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!