Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use JSON response as an array in javascript

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’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading