将对象转换为对象列表javascript

sqyvllje  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(333)

我正在构建一个api,将电影添加到愿望列表中。我有一个终点,让所有的电影在愿望清单。我的方法是获取电影ID(不是来自mongodb)并向另一个api发出api请求以获取电影对象。
到目前为止,这是成功的,但现在的问题是我将两个对象融合为一个对象,如下所示:

{
   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>',
}

这是下面的第二个对象。注意,两个对象之间没有逗号分隔

{
  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>",

}

我现在的问题是如何将这两个对象转换为数组,并从自己的api作为响应发送。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
}

我尝试创建一个空数组。 shows.data 这是实际的响应,然后我尝试使用 showsArr.push(shows.data) 以前没有多少成功。我明白了 undefined 当我登录到控制台时。

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

我将如何实现这一目标?谢谢

sf6xfgos

sf6xfgos1#

就像在转换 wishlist 数组到ID数组,您需要 push 将数据项添加到新的 showsArr .
但是,这实际上不起作用,因为它是异步的——您还需要使用 Promise.all 一系列的承诺。实际上你不应该使用 push 毫无疑问 map A. map 调用已经为您创建了一个包含回调返回值的数组。因此,您可以将代码简化为

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);
        }
    }
};

相关问题