我有一个带有两个数组的json文件,其中一个是嵌套的。我需要从嵌套数组中获取数字,并将它们与unnested数组中的值(id)匹配,以便我可以将unnested数组中的匹配值发送到另一个函数。我一直试图弄清楚这一点,并且无法弄清楚我做错了什么。任何指针或帮助将不胜感激。
我将数据提供给我的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 :(得分:0)
只需迭代类别并找到视频:
IOptions
或者,如果您只想获取嵌套类别中提到的视频:
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
}
}
答案 1 :(得分:0)
您可以像这样简单map
对视频数组:
const videoIds = data.videos.map(video => video.id);
console.log(videoIds)
这将返回一个包含视频数组中所有id
的数组。