我有一个数组对象,在该数组对象中,我需要根据isVerfied属性过滤并创建一个数组。如果isVerfied属性为真,我只需要推送对象的 name 属性而不是将整个对象推送到数组中我试过这个,但它似乎没有工作,因为它正在推动整个对象。const users = [ { name: 'Varun', age: '18', isVerfied: 'true' }, { name: 'Rahul', age: '12', }] const verfiedUserNameNew = users.filter(user => { if (user.isVerfied) return user.name})console.log(verfiedUserNameNew) 我也试过地图const users = [ { name: 'Varun', age: '18', isVerfied: 'true' }, { name: 'Rahul', age: '12', },] const verfiedUserNameNew = users.map(user => { if (user.isVerfied) return user.name})console.log(verfiedUserNameNew)但随后它返回 varun 和 undefined。我知道另一种解决方案是创建一个数组并运行一个 for.Each 循环,在该循环中放置一个 if 条件,然后将元素推入一个数组中const users = [ { name: 'Varun', age: '18', isVerfied: 'true' }, { name: 'Rahul', age: '12', },] const newArray = []users.forEach(element => { if (element.isVerfied) { newArray.push(element.name) } }) console.log(newArray)但我在想我们是否可以使用过滤方法来实现这一点?
2 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
您可以使用 reduce
const users = [{name: 'Varun',age: '18',isVerfied: 'true'},{name: 'Rahul',age: '12',},]
const verfiedUserNameNew = users.reduce((op,{name,isVerfied}) => {
if (isVerfied) op.push(name)
return op
}, [])
console.log(verfiedUserNameNew)
添加回答
举报
0/150
提交
取消