简体   繁体   English

迭代对象数组并在反应中使用自定义键名映射它们

[英]Iterating over an array of objects and mapping them with custom key names in react

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.我正在尝试遍历对象数组并将它们作为道具分配给 react Plyr 组件,这是我目前正在做的事情,我只是将第一个 object 值作为道具传递给组件,就像这样。

    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这是我的 api 回复

"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 .这是 plyr object 的结构与 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.我对 React 还是新手,我确实尝试使用 for each 和 map 但我无法更改键名,基本上我想存储来自 api 响应的键值并将它们分配给自定义键。

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
        }

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)

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

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