Home > OS >  How to use JSON response as an array in javascript
How to use JSON response as an array in javascript

Time:12-15

Here is my response I get from API request:

[ 'bookShelf3', 'bookShelf4', 'bookShelf5' ]

Here is a part of my code which searches through my mongoDB Databese:

const responseToSearchC = (req, res) => {
  console.log(req.body.searchTerm);
  db.collection('subtitle')
    .find({
      series: { $in: ['bookShelf1'] },
      $text: { $search: req.body.searchTerm },
    })

I just want to make my code dynamic and instead hard coding ['bookShelf1'] set its value by JSON response. the problem is the response from API is an object (although it is look like an array) and I cannot replace it with my hard codded array ['bookShelf1']

I tried to stringify it but it didn't work cuz its a string again, and not an array like hardcoded one

CodePudding user response:

If the response is really an object like:

{ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'}

you can simply utilize the Object.values() method which returns all of the object's values as an array.

Here's an example:

let ob={ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'};
console.log(Object.values(ob));

  • Related