Home > Blockchain >  JavaScript - Object creating with reduce method and ({}) meaning
JavaScript - Object creating with reduce method and ({}) meaning

Time:04-11

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

CodePudding user response:

- 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 });

  • Related