Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading