I have an array object and inside that array object I need to filter and create an array based on isVerfied property.
If isVerfied property is true, I just need to push the name property of the object instead of pushing the entire object into an array
I tried this but it doesn't seem to be working since it is pushing the entire object.
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)
I tried with map as well
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)
But then it return varun and undefined. i know an alternate solution can be to create an array and run a for.Each loop, put an if condition inside that loop and then push the element into an array
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)
But I was thinking if we could achieve this using filter method?