-2

I am not sure how to accurately describe this issue, but the code should suffice. This code is in React.js, but I think it is a JavaScript question more than anything. I have a variable initialization:

const key = this.state.key;

This will evaluate to one of three strings...title, author, or year. How can I use this variable in the following block?

let filteredBooks = books.filter(
  (book) => {
    return book.key.toString().toLowerCase().indexOf(this.state.query) !== -1;
  }
);

Book has properties title, author, and year... that I want to query, and I would rather not switch through the possible values of key(only 3 right now), in case I want to scale with more properties for the book object later. How can I dynamically reference key, and render it on the fly to either title, author, year, or any other property that key might be. (key is not a property of book). I have tried book.eval(key), but this throws an "undefined is not a function" compilation error at eval(key). Once again, I am using React.js but I am thinking this is a general Javascript question. Thanks!

  • 3
    `book[key]` with bracket notation? – Andrew Li Oct 24 '16 at 23:39
  • I'm maybe not understanding the question, but if you have an object book, and you want to get the value of book based on a var called key, it would be `book[this.state.key]` – Keith Oct 24 '16 at 23:39
  • 1
    @user6711198 Get rid of that dot there: `return book[key].toString()....` read a basic JS tutorial about properties – Andrew Li Oct 24 '16 at 23:44
  • BOOOOM. Thanks guys. I knew it was simple, just didn't know how to phrase the google search. Thanks Andrew Li and Keith for your quick response! – user6711198 Oct 24 '16 at 23:46
  • haha yeah silly mistake there Andrew..thanks again! – user6711198 Oct 24 '16 at 23:47
  • book[key] is the solution! – user6711198 Oct 24 '16 at 23:47
  • My head is all messed up from learning React and trying to do things the React way...thanks again! – user6711198 Oct 24 '16 at 23:49
  • My understanding of your question is that you have an object of books and you want to iterate over it and simply get the books that have a specific key: vlaue pair. If that is correct. This would be done much more quickly with javascript regex. – Urasquirrel Oct 24 '16 at 23:56

1 Answers1

1

book[key] is the correct answer posted by Answer Li and Keith in the comments!