简体   繁体   English

将对象转换为对象列表 Javascript

[英]Convert Objects to List of Objects Javascript

I'm building an API to add movies to wishlist.我正在构建一个 API 来将电影添加到愿望清单。 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.我的方法是获取电影 ID(不是来自 mongodb)并向另一个 API 发出 API 请求以获取电影对象。

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 发送。 API code is below: API代码如下:

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. shows.data这是实际的响应,然后我尝试使用showsArr.push(shows.data)将它添加到我的数组中,但没有取得多大成功。 I get undefined when I log to console.当我登录到控制台时,我得到了undefined

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 .就像将wishlist数组转换为 id 数组一样,您需要push数据项push送到新的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.然而,这实际上并不起作用,因为它是异步的——你还需要等待它们,在一系列承诺上使用Promise.all 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.而且您实际上根本不应该将pushmap一起使用, map调用已经为您创建了一个包含回调返回值的数组 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);
        }
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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