Home > Blockchain >  Iterating over an array of objects and mapping them with custom key names in react
Iterating over an array of objects and mapping them with custom key names in react

Time:12-08

I am trying to loop through an array of objects and assign them as props to the react Plyr component here is what i am doing currently i'm just passing the first object values as props to the components like so.

    if (movie) {
        console.log(movie.video_info[0].src)
        videoSrc = {
            type: 'video',
            title: 'Example title',
            sources: [
                {
                    size: movie.video_info[0].quality,
                    src: movie.video_info[0].source
                }
            ]
        }
    };

here is my api response

"video_info": [
    {
        "quality": "1080",
        "video_url": "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
        "id": "1111"
    },
    {
        "quality": "720",
        "video_url": "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4",
        "id": "1112"
    }
]

here is what the structure of the plyr object is link to plyr io.

I am still new to React and i did try using for each and map but i was not able to change the key names basically i want to store the key values from the api response and assign them to custom keys.

CodePudding user response:

Are you trying to do this?

let a = movie.video_info.map( v => {
    return {
        type:'video',
        title: 'Example title',
        sources: [{
            size: v.quality,
            src: v.video_url
        }]
    }
})

console.log(a)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You mean. mapping over an array of sources?

let sources = movie.video_info
                   .map((vidInfo)=>({
                       size: vidInfo.quality,
                       src: vidInfo.source
                     }))

let videoSrc = {
            type: 'video',
            title: 'Example title',
            sources
        }
  • Related