0

I want to dynamically call different database collections in my app based on a string like below:

const collection = 'books';
db.${collection}.find()  // turns into db.books.find()

I am using ES6, so if there are any easy ways to do this that would be great! I've been unable to find the way to create this.

EDIT: I am not trying to access part of a object, but anywhere. I'd also want to do something like

${collection}.db.find()

2 Answers2

1

Every property on a JavaScript object can be accessed using square brackets. Like this:

const collection = 'books';
db[collection].find()
arjabbar
  • 6,044
  • 4
  • 30
  • 46
0

In case of dynamic strings you should use the format

db[collection].find() // turns into db['books'].find()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

object.property
object['property']

are same.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307