简体   繁体   中英

Convert Objects to List of Objects Javascript

I'm building an API to add movies to wishlist. I have an endpoint to get all movies in wishlist. My approach was to get the movie ids (not from mongodb) and make an API request to another API to get the movie objects.

This has been successful so far but the problem now is I am getting two objects fused into one object like below:

{
   id: 7,
   url: 'https://www.tvmaze.com/shows/7/homeland',
   name: 'Homeland',
   language: 'English',
   genres: [ 'Drama', 'Thriller', 'Espionage' ],  
   status: 'Ended',
   runtime: 60,
   averageRuntime: 60,
   premiered: '2011-10-02',
   officialSite: 'http://www.sho.com/sho/homeland/home',
   schedule: { time: '21:00', days: [ 'Sunday' ] },
   rating: { average: 8.2 },
   image: {
      medium: 'https://static.tvmaze.com/uploads/images/medium_portrait/230/575652.jpg',
      original: 'https://static.tvmaze.com/uploads/images/original_untouched/230/575652.jpg'
   },
  summary: '<p>The winner of 6 Emmy Awards including Outstanding Drama Series, <b>Homeland</b> is an edge-of-your-seat sensation. Marine Sergeant Nicholas Brody is both a decorated hero and a serious threat. CIA officer Carrie Mathison is tops in her field despite being bipolar. The delicate dance these two complex characters perform, built on lies, suspicion, and desire, is at the heart of this gripping, emotional thriller in which nothing short of the fate of our nation is at stake.</p>',
}

This is the second object below. Notice how there's no comma separating both objects

{
  id: 1,
  url: 'https://www.tvmaze.com/shows/1/under-the-dome',
  name: 'Under the Dome',
  language: 'English',
  genres: [ 'Drama', 'Science-Fiction', 'Thriller' ],
  status: 'Ended',
  runtime: 60,
  averageRuntime: 60,
  premiered: '2013-06-24',
  schedule: { time: '22:00', days: [ 'Thursday' ] },
  rating: { average: 6.6 },
  image: {
     medium: 'https://static.tvmaze.com/uploads/images/medium_portrait/81/202627.jpg',
     original: 'https://static.tvmaze.com/uploads/images/original_untouched/81/202627.jpg'
  },
  summary: "<p><b>Under the Dome</b> is the story of a small town that is suddenly and inexplicably sealed off from the rest of the world by an enormous transparent dome. The town's inhabitants must deal with surviving the post-apocalyptic conditions while searching for answers about the dome, where it came from and if and when it will go away.</p>",

}

My question now is how do I convert both objects to an array and send as a response from my own API. API code is below:

module.exports = {
fetchAll: async (req, res, next) => {
  
    var idsArr = [];
    var showsArr;
    var shows;
   
    try {
        let wishlist = await Wishlist.find({});
        if (wishlist == null) {
            res.status(404)
                .json({
                    success: false,
                    msg: 'No Movies Found in Wishlist',
                    wishlist: []
                })
        }
        // console.log(wishlist);
        wishlist.map((item) => {
            idsArr.push(item.id);
        })
        console.log(idsArr);
        idsArr.map(async (id) => {
            shows = await axios.get(`https://api.tvmaze.com/shows/${id}`);
            console.log(shows.data);
            // console.log(showsArr);
            // showsArr = [shows.data];
        })
        console.log(showsArr);
        return res.status(200)
                  .json({
                    success: true,
                    msg: 'All Movies in Wishlist Fetched',
                    wishlist: showsArr
                  })
    } catch (err) {
        console.log(err);
        next(err);
    }
},
... // other methods
}

I have tried creating an empty array. shows.data which is the actual response and then I've tried adding it to my array using showsArr.push(shows.data) previously without much success. I get undefined when I log to console.

Here the ids range from 1 to 240+, in case one wants to try out the endpoint - https://api.tvmaze.com/shows/${id}

How would I go about achieving this? Thanks.

Just like when converting the wishlist array to an array of ids, you would need to push the data items into your new showsArr .

However, this doesn't actually work, since it's asynchronous - you also need to wait for them, using Promise.all on an array of promises. And you actually shouldn't be using push at all with map , a map call already creates an array containing the callback return values for you. So you can simplify the code to

module.exports = {
    async fetchAll(req, res, next) {
        try {
            const wishlist = await Wishlist.find({});
            if (wishlist == null) {
                res.status(404)
                    .json({
                        success: false,
                        msg: 'No Movies Found in Wishlist',
                        wishlist: []
                    })
            }
            const idsArr = wishlist.map((item) => {
//          ^^^^^^^^^^^^^^
                return item.id;
//              ^^^^^^
            });
            console.log(idsArr);
            const promisesArr = idsArr.map(async (id) => {
                const show = await axios.get(`https://api.tvmaze.com/shows/${id}`);
                console.log(shows.data);
                return shows.data;
//              ^^^^^^^^^^^^^^^^^^
            });
            const showsArr = await Promise.all(promisesArr);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            console.log(showsArr);
            return res.status(200)
                      .json({
                        success: true,
                        msg: 'All Movies in Wishlist Fetched',
                        wishlist: showsArr
                      })
        } catch (err) {
            console.log(err);
            next(err);
        }
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM