1

I am trying to figure out why the following code results in an array of objects:

const startingArray = ['One', 'Two', 'Three', 'Four', 'Five'];

let endingArray = startingArray.map((nums) => {
  return { nums }
});

console.log(endingArray)

The result would be an array of objects such as:

[{nums: 'One'}
{nums: 'Two'}...]

and continuing on through the end of the input array... I understand that the map() method creates a new array populated with the results of calling a provided function on every element in the calling array. So is it simply a matter of the fact that by wrapping the argument in curly braces the map method inherently sets the argument name as the key of an object literal and sets the value of the input array as the associated value of the respective key?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Austin737
  • 675
  • 1
  • 8
  • 15
  • 2
    @DavidThomas No it's not – Bergi Oct 12 '21 at 08:07
  • 1
    And you can even do this `let endingArray = startingArray.map(nums => ({ nums }));` – mplungjan Oct 12 '21 at 08:08
  • 1
    "*So is it simply a matter of the fact that by wrapping the argument in curly braces the map method inherently sets …?*" - no, this has nothing to do with the `map` method or `nums` being a parameter of the callback function. It's just object literal syntax, and works also everywhere else. The `map` method doesn't care how the callback produces its results. – Bergi Oct 12 '21 at 08:10
  • @Bergi ok your comment is very helpful to me, and I thank you. So this is also why if I wrap the param name in brackets [ ] as the return value then the result is an array of arrays, with each inner-array containing the value from the input array, correct? It is just a syntax issue and not anything to do with the map method itseft. – Austin737 Oct 12 '21 at 08:18
  • 1
    @Austin737 Yes, it's just array literal syntax in the `return` statement of that function. – Bergi Oct 12 '21 at 08:36
  • @Bergi, I need to pay more attention to what’s happening, this hobby is accelerating past me at a rate of knots these days. Thanks for the correction. – David Thomas Oct 12 '21 at 10:45

1 Answers1

-1

{num} here is shorthand to {'num' : num} Checkout x in the below code:

let a = 22;
let x = { a};
console.log(x);

const startingArray = ['One', 'Two', 'Three', 'Four', 'Five'];

let endingArray = startingArray.map((nums) => {
    return {nums}
});
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39