Array.map takes in a callback function as its argument, here it is: ({ Title: title, imdbRating: rating }) => ({title, rating})
.
Or if you ignore all the words and stuff and look at the curly brackets, which can only mean it defines an object, then you can see it is (obj)=>obj
, where it takes in an object, and returns an object.
Now to take a closer look at the object used as the parameter for the callback: { Title: title, imdbRating: rating }
. What it means is even though you get a object with however many keys passed in, it only looks for two keys: Title
, and imdbRating
, and their value which gets assigned to the variable names title
and rating
respectively. Here is what I mean:
const arrOfObj=[
{A:'valA1',
B:'valB1'
C:'valC1'},
{A:'valA2',
B:'valB2',
C:'valC2'}];
arrOfObj.map(({A:a,B:b})=> console.log(a,b));
//will print 'valA1 valB1' and 'valA2 valB2' and ignore the key C
note how i also assigned the value of key A to the variable a
, and value of key B to the variable b
. That’s how the console.log know what to print.
now onto the returned object {title, rating}
, which looks probably a little odd, since objects are supposed to have key:value pairs and this looks like its only got values. Well in cases where you directly return a numbe of variables within curly brackets, JS actually assigns keys to the values based on their variable name. Here is what I mean.
let num1 = 3;
let num2 = 4;
const toObj=(a,b)=>{
return {a,b};
}
console.log(toObj(num1,num2));
//prints {a:3,b:4}
This entire thing is called object destructuring and is immensely useful and convenient once you learn it.