我试图在将对象数组发送到后端之前对其进行过滤。它应该以没有虚假值的方式进入后端。如果我这样做,它会起作用:theArray.filter(({ name }) => name)但我需要再添加一个属性:theArray.filter(({ name, percentage }) => { return { percentage, name } }),如果我像上面那样做,它不起作用,我错过了什么?
3 回答

翻过高山走不出你
TA贡献1875条经验 获得超3个赞
您的过滤器函数应返回一个布尔值,以确定是否保留数组元素:
theArray.filter(({name, percentage}) => {return name && percentage});
要不就
theArray.filter(({name, percentage}) => name && percentage);

隔江千里
TA贡献1906条经验 获得超10个赞
因此,您目前正在做的是从数组中的每个对象中提取 name 属性,然后对其进行“真实”测试。
对于一个字符串(大概类似名称),这意味着undefined
,null
和空字符串将等同为false。
对于一个数字(大概是百分比),这意味着undefined
,null
并且0
将等同于 false。
在这种情况下,您可以使用以下内容(牢记上述注意事项):
theArray.filter(({ name, percentage }) => percentage && name)
添加回答
举报
0/150
提交
取消