Home > Net >  Array / objects - getting object by id returning all the data
Array / objects - getting object by id returning all the data

Time:07-13

I have some data that looks like this:

[
   {
      "item":{
         "Name":"Name1",
         "working":true,
         "extra":{
            "active":true
         }
      },
      "id":2
   },
   {
      "item":{
         "Name":"Name2",
         "working":true,
         "extra":{
            "active":true
         }
      },
      "id":4
   }
]

I also have the 'id' that I need.

So basically I need to get the object which contains the id required.

I'm trying this:

const item = myDat.find(item => item.id === '4');

console.log(item); // returns all the data and not the one I need

It's currently giving me all the data and not the object I need.

How can I fix this?

CodePudding user response:

your code can't find the item because you are comparing 4 === "4" which are different. one is string the other one is number.

const item = myDat.find(item => item.id === '4');

change this to

const item = myDat.find(item => item.id === 4);

CodePudding user response:

The first issue that I see is that the id field is type number, but you are comparing it with a string ('4'). You should compare it like: item.id === 4.

Secondly, find returns either an item or undefined (see them enter image description here

Change myDat.find(item => item.id === '4') to myDat.find(item => item.id === 4)

  • Related