Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically access object field

I am refactoring Vuex and I have a common action such as:

 deleteFromList ({commit}, {list = '', type = '', listPlural = '', data = {}}) {
  db.rel.find(list, data).then(doc => {
    return db.rel.del(list, doc.rooms[0])
  })
}

If list is set to room, it returns a response doc.rooms. So an object containing a rooms array.

In this case listPlural param would be passed with a value of rooms.

How do I return doc.rooms[0] dynamically using listPlural param instead?

Something like doc.listPlural[0], just to give an idea.

like image 397
catmal Avatar asked Feb 23 '26 22:02

catmal


1 Answers

You could access the doc field using brackets notation like :

 deleteFromList ({commit}, {list = '', type = '', listPlural = '', data = {}}) {
  db.rel.find(list, data).then(doc => {
   if(listPlural){// check if the listPlural is not empty
      return db.rel.del(list, doc[listPlural][0])
   }
  })
}
like image 116
Boussadjra Brahim Avatar answered Feb 26 '26 12:02

Boussadjra Brahim