Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

javascript - How to use ES6 Fat Arrow to .filter() an array of objects

I'm trying to use ES6 arrow function with .filter to return adults (Jack & Jill). It appears I cannot use an if statement.

What do I need to know in order to do this 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; }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It appears I cannot use an if statement.

Arrow functions either allow to use an expression or a block as their body. Passing an expression

foo => bar

is equivalent to the following block

foo => { return bar; }

However,

if (person.age > 18) person

is not an expression, if is a statement. Hence you would have to use a block, if you wanted to use if in an arrow function:

foo => {  if (person.age > 18) return person; }

While that technically solves the problem, this a confusing use of .filter, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to .filter should return a Boolean, i.e. true or false, indicating whether the element should be included in the new array or not.

So all you need is

family.filter(person => person.age > 18);

In ES5:

family.filter(function (person) {
  return person.age > 18;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...