2017-11-17 59 views
-1

我有一个带有两个数组的json文件,其中一个嵌套。我需要从嵌套数组中获取数字,并将它们与未占用数组中的值(id)进行匹配,以便我可以将未使用数组中的匹配值发送到另一个函数。我一直试图找出连续两天的情况,并没有能够弄清楚我做错了什么。任何指针或帮助将不胜感激。从嵌套数组中获取特定值

我有数据给我的json在这里作为参考。

{ 
    "videos": [ 
    { 
     "id": 1, 
     "title": "Lego!", 
     "created": 1509804047011, 
     "duration": 5, 
     "poster": "./videos/small.png", 
     "video": "./videos/small.mp4" 
    }, 
    { 
     "id": 2, 
     "title": "Big Bunny", 
     "created": 1507804047011, 
     "duration": 62, 
     "poster": "./videos/bunny.png", 
     "video": "./videos/bunny.mp4" 
    }, 
    { 
     "id": 3, 
     "title": "Prufu myndband", 
     "created": 1505904047011, 
     "duration": 3600, 
     "poster": "./videos/16-9.png", 
     "video": "./videos/bunny.mp4" 
    }, 
    { 
     "id": 4, 
     "title": "Prufu myndband með löngum texta sem fer í tvær línur", 
     "created": 1504904047011, 
     "duration": 220, 
     "poster": "./videos/16-9.png", 
     "video": "./videos/bunny.mp4" 
    } 
    ], 

    "categories": [ 
    { 
     "title": "New videos", 
     "videos": [1, 2] 
    }, 
    { 
     "title": "Amazing videos", 
     "videos": [1, 3, 4] 
    }, 
    { 
     "title": "Funny videos", 
     "videos": [2, 3, 4] 
    } 
    ] 
} 

回答

0

只是遍历类别,并找到视频:

for(const {title, videos} of data.categories){ 
    for(const id of videos){ 
    const video = data.videos.find(v => v.id === id); 
    //do whatever with video 
    } 
} 

或者,如果你只是想获得那些在嵌套类中提到的视频:

const ids = new Set(data.categories.reduce((res, videos) => res.concat(videos))); 

const result = data.videos.filter(v => ids.has(v.id)); 
+0

感谢哥们,会看到它是如何变成:) –

0

你可以只需map这样的视频阵列:

const videoIds = data.videos.map(video => video.id); 
console.log(videoIds) 

这将返回一个数组,其中包含视频数组中的所有id

+0

谢谢我会尝试和使用这个,我会给你一个反馈它是如何工作的。 –

相关问题