Im learning javascript and looking over some code and ran into this:
array.map(item => item[prop])
where prop may be something like 'id'
or something.
I haven't been able to find an actual example of this on the web. So I tried just doing something like this:
property = 'id'; var arr = [1,2,3,4]; var something = arr.map(item => item[property]); console.log(something);
This doesn't work however. And I can't seem to find an example on the web. Is this a new type of syntax for the map function?
The "arrow function" is a shorthand way of writing functions.
item => item[property]
It is (mostly) equivalent to writing:
function(item){ return item[property]; }
Your arr
array contains numbers, so in the function item
will be a number. Numbers do not have an 'id'
property, so that's why it "doesn't work".
Consider if you had something like:
var prop = 'id'; var arr = [{id:1, name:"one"}, {id:2, name:"two"}]; var something = arr.map(item => item[prop]); console.log(something);
something
would end up being [1, 2]
.