Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use filter to extract the desired value from the values ​of the double objects in the array?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading