2017-11-17 71 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

謝謝我會嘗試和使用這個,我會給你一個反饋它是如何工作的。 –

相關問題