Home > Software design >  How to extract an Array from API response
How to extract an Array from API response

Time:10-27

Hello I am using https://www.npmjs.com/package/ytfps package to get the URLs and titles from youtube playlists. The format given as response to ytfps(url).then(playlist =>{console.log(util.inspect(playlist))} is the following:

{
   title: 'Music Playlist',
   url: 'https://www.youtube.com/playlist?list=PLoXvI0xCls_7WZpfvrqwBNqlnZTMylyTvdo6',
   id: '7WZpfvrqwBNqlnZTMylyTvdo6',
   video_count: 16,
   view_count: 16,
   description: '',
   isUnlisted: false,
   thumbnail_url: 'https://i.ytimg.com/vi/jBmkNzfqFZUSW4/hqdefault.jpg',
   author: {
     name: 'Default',
     url: 'https://www.youtube.com/user/gadfgagaq',
     avatar_url: 'https://yt3.ggpht.com/ytc/AKedOLQoEJLXJMV2t3MRgadfqNuhWk46GwnYr7r1DAgnGbsQ=s176-c-k-c0x00ffffff-no-rj'
   },
   videos: [
     {
       title: 'Barei - Say Yay! (Eurovision 2016 Spain)',
       url: 'https://www.youtube.com/watch?v=jBmkNzFZUW4',
       id: 'jBmkNzFZUW4',
       length: '3:07',
       milis_length: 187000,
       thumbnail_url: 'https://i.ytimg.com/vi/jBmkNzFZUW4/hqdefault.jpg',
       author: [Object]
     },
     {
       title: 'Sound of Silence',
       url: 'https://www.youtube.com/watch?v=4S6sT_2gM2o',
       id: '4S6sT_2gM2o',
       length: '3:16',
       milis_length: 196000,
       thumbnail_url: 'https://i.ytimg.com/vi/4S6sT_2gM2o/hqdefault.jpg',
       author: [Object]
     },

   ]
}

What I want is to get 2 arrays one of URLs and the other one of titles, like this:

url= [https://www.youtube.com/watch?v=jBmkNzFZUW4', 'https://www.youtube.com/watch?v=4S6sT_2gM2o', and so on... ]
titles =['Barei - Say Yay! (Eurovision 2016 Spain)', 'Sound of Silence', and so on ]

So what is the best way to extract those 2 arrays?

CodePudding user response:

You need just to iterate videos. Then, for each video, you extract the url and put the result in an urls array. The same for the title, you extract the title and put the result in an titles array.

Something like :

const urls = [];
const titles = [];

playlist.videos.forEach(video => {
    urls.push(video.url);
    titles.push(video.title);
});

console.log(urls);
console.log(titles);

CodePudding user response:

You can declare two separate arrays, map the videos array on your object and push to those arrays accordingly,

Like:


const videoTitle = [];

const videoUrl = [];

videos.map(v => {
  
    videoTitle.push(v.title)
    videoUrl.push(v.url);
});
  
  • Related