I have an object in an array called pick and I also have another object called diaryItem.
I also want to extract only the object whose name is wormColor from the diaryItem object.
so i tried my code but it doesn’t work
error says v.filter is not a function
How can i fix my code?
const pick = [
{
diaryId: 1,
diaryItem: { name: 'instar' }
},
{
diaryId: 2,
diaryItem: { name: 'facebook' }
},
{
diaryId: 1,
diaryItem: { name: 'wormColor' }
},
]
const wormcolor = pick.map((v) => v.filter((p) => p.name ==="wormColor"))
expected answer
wormcolor : [{
diaryId: 2,
diaryItem: { name: 'wormColor' }
value: "2"
}]
or
wormcolor : {
diaryId: 2,
diaryItem: { name: 'wormColor' }
value: "2"
}
>Solution :
You need map() when you want to transform an array into another of same length by applying some function. That is not appropriate here.
Also, looking at your filter() callback, you are accessing .name directly, instead you want .diaryItem.name:
const pick = [
{
diaryId: 1,
diaryItem: { name: 'instar' }
},
{
diaryId: 2,
diaryItem: { name: 'facebook' }
},
{
diaryId: 1,
diaryItem: { name: 'wormColor' }
}
]
const wormcolor = pick.filter((p) => p.diaryItem.name ==="wormColor");
console.log(wormcolor);