Home > Software engineering >  Returning the value of one element of an object in an array of objects in Vue
Returning the value of one element of an object in an array of objects in Vue

Time:01-17

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

CodePudding user response:

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.

CodePudding user response:

I don't know why you are trying to use array.find

but if you are trying to get the find or filter from an array.

It's better to use array.filter. Because array.find will return only the 1st value of the element that it match. If there are multiple matches it will ignore the the rest.

const array = [{name:'user1', id: 1}, {name:'user2', id: 2}];

const result = array.filter(person => person.name === 'user1');

console.log(result)
  • Related