0

I have a similar Question to this user here: Find object by id in an array of JavaScript objects

I would like to find an Object by ID in an Array ob Objects. In MDN there was an example with Array.find().

My Problem is, that the Object can be null. Here is the example:

var myArray = [
 {id:1, name:"bob"},
 {id:2, name:"dan"},
 {},
]

// grab the Array item which matchs the id "6"
var item = myArray.find(item => item.id === 6);

// print
console.log(item.name);

The third Object in the Array is null by some mistake. And so the item is null and so item.id is failing. How can I prevent this?

kvetis
  • 6,682
  • 1
  • 28
  • 48
user39063
  • 183
  • 1
  • 13
  • Not really sure what you're trying to do here, but if you expect the find item returns null, you have to create a checking to only process the data if it has a value, otherwise, handle the undefined separately – romel Mar 15 '23 at 09:08

4 Answers4

1

Not sure if i got it correctly you are saying if there is a null object instead of {} its failing in that case if so than you can use null safe operator in your condition like i=> i?.id

var myArray = [
 {id:1, name:"bob"},
 {id:2, name:"dan"},
 {},
]

// grab the Array item which matchs the id "6"
var item = myArray.find(i => i.id === 6);

// print
console.log("When item is empty object",item?.name);
var myArray = [
 {id:1, name:"bob"},
 {id:2, name:"dan"},
 null,
]
// grab the Array item which matchs the id "6"
var item2 = myArray.find(item => item?.id === 6);
console.log("When item is null",item?.name);
jitender
  • 10,238
  • 1
  • 18
  • 44
0

Please use Optional chaining (?.)

https://stackoverflow.com/a/63498539/10562084

var myArray = [
 {id:1, name:"bob"},
 {id:2, name:"dan"},
 {},
 null,
]

// grab the Array item which matchs the id "6"
var item = myArray.find(item => item?.id === 6);

// print
console.log(item?.name);
Jay
  • 2,826
  • 2
  • 13
  • 28
0

You have to check if the item exists before logging item.name.

 // print
 if (item) {
   console.log(item.name);
 } else {
   console.log('No item was found');
 }
Eylon
  • 1
  • 1
0

Here, is the simple solution for your problem.

    var myArray = [
     {id:1, name:"bob"},
     {id:2, name:"dan"},
     {},
    ];

// find in array

    var item = myArray.find(item => {if(item.id) { return item.id === 2}});

// log name

    console.log(item?.name);