-2

When I run the below code and try accessing the "id" within images using the map() method, it gives me undefined. Whereas, accessing the reId/name/dob/number is the same as console.log(d.reId)

var data = [
    {
      reId: 'huih23432',
      name: 'skdskdss',
      dob: '26/06/1998',
      number: '34535353543',
      images: {
        "id": 'https://picsum.photos/200',
        "link": 'https://picsum.photos/200',
      },
    },
    {
    "name": "x"
    }


]

data.map((d)=>{
    console.log(d.images.id)
})

I want a solution using map() method itself to access the id | link within "images" key.

Mansur
  • 1,622
  • 14
  • 27
Hrishikesh D Kakkad
  • 171
  • 1
  • 1
  • 12
  • you have to add check of key as in second object there is no image key like d && d.image && d.image.id – KCFragrance Jul 14 '20 at 18:30
  • 1
    Does this answer your question? [Access Javascript nested objects safely](https://stackoverflow.com/questions/18178406/access-javascript-nested-objects-safely) – Emile Bergeron Jul 14 '20 at 19:07

2 Answers2

2

You have to return in the map callback

var imageIds = data.map(d=>d.images && d.images.id)
       .filter(id => id); // filter out null elements
phnkha
  • 7,782
  • 2
  • 24
  • 31
2

var data = [
    {
      reId: 'huih23432',
      name: 'skdskdss',
      dob: '26/06/1998',
      number: '34535353543',
      images: {
        "id": 'https://picsum.photos/201',
        "link": 'https://picsum.photos/200',
      },
    },
    {
    "name": "x"
    }


]

data.map((d)=>{

    if (typeof d.images != 'undefined') 
    console.log(d.images.id);
})
DCR
  • 14,737
  • 12
  • 52
  • 115