Reputation: 377
not sure what is happening in .map(([key, value]) => [key, value * 2])
I have a gist idea of what the square brackets do in that parameter. But can someone clarify the rules of the syntax, or explain whats happening?
Here's my belief of how the code works:
[[banana, 1], [orange, 2], [meat, 4]]
if map's going through the items; would it make more sense to write .map((item) => [item[0], item[1] * 2])
going through a lesson from javascript.info
let prices = {
banana: 1,
orange: 2,
meat: 4,
};
let doublePrices = Object.fromEntries(
// convert to array, map, and then fromEntries gives back the object
Object.entries(prices).map(([key, value]) => [key, value * 2])
);
console.log(doublePrices.meat); // 8
Upvotes: 3
Views: 1519
Reputation: 5581
In the code snippet you're asking about the left side is quite different from the right side. Let's break it down:
.map(([key, value]) => [key, value * 2])
First, map
takes a function as its parameter. Here the function is essentially doing this:
(entry) => {
const key = entry[0];
const value = entry[1];
const modified_entry = [ key, value * 2 ];
return modified_entry;
}
A shorter way to write that is:
(entry) => [ entry[0], entry[1] * 2 ]
That works the same because without curly brackets around the function body, it uses the value as the return value.
Now the code you're asking about isn't using a single variable for the input parameter to the function. It's a single parameter, but it sets 2 variables by using something called deconstruction
or destructuring
. This is a feature in Javascript that lets you break apart an object into multiple variables in a simple way. For example look at this:
var entry = [ 'meat', 1]
var [ item, price ] = entry
// now item is 'meat', and price is 1, which is nicer than having to do this:
item = entry[0]
price = entry[1]
So getting back to your code, they've expressed entry
as [key,value]
so that they can be used in the function easily, and on the right hand side of the =>
we have the return value which is a new array with the doubled price.
Remember that on the left side we're breaking an object into new variables which get assigned values, while on the right side we're creating a new Array object that's being returned. It can be a bit confusing because they both have the same form of looking like an array in square brackets.
Note also that deconstruction works for objects as well as arrays, so this is valid code too:
var obj = { a:1, b:2, c:3 }
var { a, c } = obj
console.log(a,c) // will print "1 3"
Deconstructing an object lets you take just the parts you want out of the object and creates variables named after the key. Notice that we didn't ask for b
so there's no b
variable - it's just ignored.
Upvotes: 2