用reduce es6替换filter和map [英] replace filter and map with reduce es6

查看:385
本文介绍了用reduce es6替换filter和map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试避免使用过滤器和地图进行链接,但为什么我的reduce返回undefined?

I'm trying to avoid chaining with filter and map, but why my reduce returned undefined?

const data = [{
        value: "moto",
        passed: true
    },{
        value: "boat",
        passed: false
    }, {
        value: "car",
        passed: true
    }]

    // expected ['moto', 'car']
    // using filter and map
    data.filter(obj => obj.passed).map(obj => obj.value)

怎么了?
data.reduce((accum,obj)=> obj.checked&& [... accum,obj.value],[])

推荐答案

 (accum, obj) => obj.checked && [...accum, obj.value]

不会返回已过滤的列表,以防对象未经检查。

does not return the filtered list, in case the object is not checked.

(accum, obj) => {
  if (obj.checked) accum.push(obj.value)
  return accum;
}

因为reducer函数会这样做。

as reducer function will do that.

或将其保留为oneliner,以保持可读性:

or to keep it as a oneliner, to not maintain readability:

(accum, obj) => obj.checked ? [...accum, obj.value] : accum;

这篇关于用reduce es6替换filter和map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆