如何从嵌套数组中检索ID?
最初,我得到这样的json响应,我需要从所有嵌套数组中获取所有id。
有人可以帮我吗?
我应该使用过滤器还是任何查找功能?
一个例子或解释可能很棒。
{
"id": 271,
"name": "anything",
"description": null,
"entries": [
{
"id": "fda2afe0-dfc4-4373-9e50-8b140a46f25e",
"name": "first occurence",
"runs": [
{
"id": 284,
"name": "the element from which I want to get id",
"description": null,
"created_on": 1530627823,
"created_by": 2
},
{
"id": 285,
"name": "element for id 2",
"created_by": 2
},
{
"id": 296,
"name": "element for id 3",
"created_on": 1530710993,
"created_by": 2
}
]
},
{
"id": "a65dd3f0-3fc1-4f93-9123-f5a05ae50703",
"name": "second occurence",
"runs": [
{
"id": 272,
"name": "element for id 4",
"created_by": 2,
},
{
"id": 273,
"created_by": 2,
},
{
"id": 274,
"created_by": 2,
}
]
}
]
}
答案 0 :(得分:2)
假设您要查找最深的ID(运行ID),下面是一个示例,介绍了如何完成此操作。
dd = data.table::fread("Name, Day, Score, Diff
Jain, 1, 8, 0
Jain, 2, 6, -2
Jain, 3, 8, 2
Jain, 4, 12, 4
Jain, 5, 13, 1
Jain, 6, 6, -7
Matt, 1,4, 0
Matt, 2, 10, 6
Matt, 3, 11, 1
Matt, 4, 12, 1
Matt, 5, 5, -7
Matt, 6, 6, 1")
答案 1 :(得分:1)
假设您将json存储在某个变量中,例如json
,
const ids = json.entries.map(entry => entry.runs.map(run => run.id));
应该为您提供一组嵌套的ID,看起来像这样
[ [ 284, 285, 296 ], [ 272, 273, 274 ] ]
。
如果您希望将其包含在一个维度列表中,即
[ 284, 285, 296, 272, 273, 274 ]
,
const concatIds = [].concat.apply([], ids);
答案 2 :(得分:1)
过滤和查找功能将是多余的,因为您将获得所有ID而不是特定ID。要解决您的问题,您只需使用map
的函数即可。在此示例中,您的对象将称为exampleObj
,在其中您可以简单地执行以下操作以获取所有ID的数组:
exampleObj.entries.map(entryObj => {
return entryObj.runs.map(runObj=>{return runObj.id});
});