0

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"
  }
user19476497
  • 495
  • 1
  • 10

3 Answers3

2

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);
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
0

You could try it with filter

var lookingFor=pick.filter(function (el){
      return el.diaryItem.name=='wormColor';
    })
0

If you want to change the object you get back then you would have to filter first and then map, something like this:

const pick = [
  {
    diaryId: 1,
    diaryItem: { name: "instar" },
  },
  {
    diaryId: 2,
    diaryItem: { name: "facebook" },
  },
  {
    diaryId: 1,
    diaryItem: { name: "wormColor" },
  },
];

const wormcolor = pick
  .filter((item) => item.diaryItem.name === "wormColor")
  .map((filtered) => {
    return {
      ...filtered,
      value: filtered.diaryId + "",
    };
  });

What you get back from this should look like this: [ { diaryId: 1, diaryItem: { name: 'wormColor' }, value: '1' } ]. If you do not want to change the original object then just skip the .map part.

Joacim Norbeck
  • 203
  • 1
  • 6