我正在尝试用 javascript 编写一个函数,该函数从 JSON 输入数据返回属于特定组的数据,包括该组的子组。数据如下所示:
[
{"id":"0", "name":"Person 0"},
{"id":"1", "name":"Person 1","group":"0"},
{"id":"2", "name":"Person 2","group":"0"},
{"id":"3", "name":"Person 3","group":"2"},
{"id":"4", "name":"Person 4","group":"2"},
{"id":"5", "name":"Person 5","group":"4"},
{"id":"6", "name":"Person 6","group":"4"},
{"id":"7", "name":"Person 7","group":"0"},
{"id":"8", "name":"Person 8","group":"7"}
]
这里,组 x 中的人与 id x 的人属于同一组。
例如:function(data, group) 将为 function(data, 2) 返回以下内容:
[
{"id":"3", "name":"Person 3","group":"2"},
{"id":"4", "name":"Person 4","group":"2"},
{"id":"5", "name":"Person 5","group":"2"},
{"id":"6", "name":"Person 6","group":"2"},
]
和功能(数据,0):
[
{"id":"1", "name":"Person 1","group":"1"},
{"id":"2", "name":"Person 2","group":"2"},
{"id":"3", "name":"Person 3","group":"2"},
{"id":"4", "name":"Person 4","group":"2"},
{"id":"5", "name":"Person 5","group":"2"},
{"id":"6", "name":"Person 6","group":"2"},
{"id":"7", "name":"Person 7","group":"7"},
{"id":"8", "name":"Person 8","group":"7"}
]
我试图循环遍历数组,但这不处理子组,所以我想我必须以递归方式来做?