Home > database >  How to update object's array of objects using map function
How to update object's array of objects using map function

Time:08-31

I'm trying to update user's role that is in array of objects, is it possible somehow to do this like in example below? I was trying also doing double map, but then my user information was deleted.

Example:

const [users, setUsers] = useState([{
    id: 1,
    login: 'abc',
    roles: [{
      admin: false
    }, {
      student: true
    }]
  },
  {
    id: 2,
    login: 'abc2',
    roles: [{
      admin: false
    }, {
      student: true
    }]
  },
])
let id = 1

setUsers(
  users.map((val) => {
    return val.id == id ? {
      ...val,
      [{
        admin: false
      }]
    } : val;
  })

);

CodePudding user response:

This is a classic use-case for Array.filter

Example:

setUsers(users.filter(user => {
   if (val.id === id) {
      return {
         ...user,
         roles: user.roles.filter(role => {
            // Determine if we are in the "right role" by checking if the `admin` field exists.
            if (role.admin !== undefined) {
               return {
                  // Here we actually update the wanted value.
                  admin: false,
               }
            }
            // If not the correct role, then just return it.
            return role;
         })
      }
   }
   // If not the wanted user, just return it as is,
   return user;
}))

I think this should work, but it's quite complex.
I would suggest altering the types if possible,
as it feels like roles should be an object, not an array of objects.

Also, note the use of === instead of the looser == comparison.
Usually you'd want to avoid using == in JS.

  • Related