Returning the value of one element of an object in an array of objects in Vue

Using the map method I am creating a new array (updated) from an existing array (data) and looking up a third array (members) using a Vue getter and it’s working fine if I want to return the member object as below…

const updated = data.map(el => ({
      ...el,
      memberId: getters.members.find(m => m.accountKey === el.dataKey)
    }))

However, when I try to return just the member object id, by adding ‘.id’ below, I get an type error ""TypeError: Cannot read properties of undefined (reading ‘id’)"

const updated = data.map(el => ({
      ...el,
      memberId: getters.members.find(m => m.accountKey === el.dataKey).id
    }))

I need to return the id not the entire member object

>Solution :

This happens because no object matches m => m.accountKey === el.dataKey in members.
To fix it, you can add a check for the existence of the member object before trying to access its ‘id’ property. One way to do this is to use the ternary operator to check if the member object exists before trying to access its ‘id’ property.

const updated = data.map(el => ({
...el,
memberId: getters.members.find(m => m.accountKey === el.dataKey) ? getters.members.find(m => m.accountKey === el.dataKey).id : undefined
}))

This will check if the member object exists before trying to access its ‘id’ property and if it does not exist it will assign undefined to the memberId property, this way you will not get the TypeError.

Leave a Reply