I am running the following in node and can't understand why one works and why the other doesn't. Here I have an array s where s = [1, 2, 3, 4]. I want to map each number to an object. I've been trying this for a long time:
s.map(i => {name: i})
which returns a list of undefined.
Finally I realized it worked with parenthesis:
s.map(i => ({name: i}))
This provides the output I want: [ { name: 1 }, { name: 2 }, { name: 3 }, { name: 4 } ]
I feel like there is a JavaScript concept I am not understanding. Why does this not work?
This is because => { represents a block function, not returning an object.
Wrapping the object in parentheses does nothing, it simply interrupts that pattern => {, meaning it's interpreted as a concise arrow function rather than a block arrow function, and you can return the object.
So, if you want to return an object, you can either wrap it in parentheses (this is the easiest way):
s.map(i => ({ name: i }));
Or use a block function:
s.map(i => {
return { name: i };
});
(on a side note, you can make your function more concise by passing in name as the map parameter name:
s.map(name => ({ name }));
As pointed out by Tomasz below, the reason that your first attempt returned a list of undefined was because name: is the syntax for a label in JavaScript - and you were just labelling name: then stating the variable i - so your code basically looked like this ES5:
s.map(function(i) {
name: i
// No return so it returns `undefined`
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With