Dynamically access object field

Viewed 81

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.

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])
   }
  })
}
Related