I am dealing with an array structure like this:
const arr = [{
name: 'One',
id: 1
},
{
name: 'Two',
id: 2
}
];
My goal is to extract and return the name of the object if its id matches a certain value.
After experimenting with different approaches, I found that my solution returned the entire object within an array instead of just the name:
const arr = [{
name: 'One',
id: 1
},
{
name: 'Two',
id: 2
}
];
const getNameFromId = id => {
return arr.filter(item => {
if (item.id === id) {
return item.name;
}
})
}
const res = getNameFromId(1)
// This should return `'One'`
console.log(res)