我有一个数组对象,并且在该数组对象内需要过滤并基于isVerfied
属性创建一个数组。
如果isVerfied
属性为true,我只需要推送对象的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)
但是我在想是否可以使用过滤器方法来实现?
答案 0 :(得分:2)
filter
和map
单独都无法做到这一点。
您有几种选择:
filter
,然后map
。这非常简单明了,并且至少适用于多达数百个或数千个条目的数组,因为它使两次通过数据(嗯,一次通过所有数据,第二次通过过滤结果) 。除非您要处理的是真正庞大的阵列,否则应该不会有任何性能问题。reduce
,这是人们通常会使用的方法,尽管坦白地说,这只是#2之上的其他复杂情况。这里是#1:
const verfiedUserNameNew = users
.filter(user => user.isVerified)
.map(({name}) => name);
实时复制:
const users = [
{
name: 'Varun',
age: '18',
isVerified: true
},
{
name: 'Rahul',
age: '12',
},
];
const verfiedUserNameNew = users
.filter(user => user.isVerified)
.map(({name}) => name);
console.log(verfiedUserNameNew);
我也在那里固定了另外两个木柄
isVerified
的拼写isVerified
使用了布尔值而不是字符串这里是#2:
const verfiedUserNameNew = [];
for (const {isVerified, name} of users) {
if (isVerified) {
verfiedUserNameNew.push(name);
}
}
实时复制:
const users = [
{
name: 'Varun',
age: '18',
isVerified: true
},
{
name: 'Rahul',
age: '12',
},
];
const verfiedUserNameNew = [];
for (const {isVerified, name} of users) {
if (isVerified) {
verfiedUserNameNew.push(name);
}
}
console.log(verfiedUserNameNew);
这里是#3,但这又是#2的更复杂,更难以阅读和调试的版本:
const verfiedUserNameNew = users.reduce((verified, {isVerified, name}) => {
if (isVerified) {
verified.push(name);
}
return verified;
}, []);
实时复制:
const users = [
{
name: 'Varun',
age: '18',
isVerified: true
},
{
name: 'Rahul',
age: '12',
},
];
const verfiedUserNameNew = users.reduce((verified, {isVerified, name}) => {
if (isVerified) {
verified.push(name);
}
return verified;
}, []);
console.log(verfiedUserNameNew);
您会看到有人这样做:
const verfiedUserNameNew = users.reduce((v, {isVerified, name}) => ((isVerified ? v.push(name) : undefined), v), []);
或类似的东西使它看起来比它简单,但是...:-)
答案 1 :(得分:2)
您可以使用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)