javascript - How to use ES6 Fat Arrow to .filter() an array of objects -
i'm trying use es6 arrow function .filter
return adults (jack & jill). appears cannot use if statement.
what need know in order in es6?
var family = [{"name":"jack", "age": 26}, {"name":"jill", "age": 22}, {"name":"james", "age": 5 }, {"name":"jenny", "age": 2 }]; let adults = family.filter(person => if (person.age > 18) person); // throws error (8:37) syntaxerror: unknown: unexpected token (8:37) |let adults = family.filter(person => if (person.age > 18) person);
my working es5 example:
let adults2 = family.filter(function (person) { if (person.age > 18) { return person; } });
it appears cannot use if statement.
arrow functions either allow use expression or block body. passing expression
foo => bar
is equivalent following block
foo => { return bar; }
however,
if (person.age > 18) person
is not expression, if
statement. hence have use block, if wanted use if
in arrow function:
foo => { if (person.age > 18) return person; }
while technically solves problem, confusing use of .filter
, because suggests have return value should contained in output array. however, callback passed .filter
should return boolean, i.e. true
or false
, indicating whether element should included in new array or not.
so need is
family.filter(person => person.age > 18);
in es5:
family.filter(function (person) { return person.age > 18; });
Comments
Post a Comment