Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从孩子们只知道父母的文档中获取ID列表_Javascript_Json_Browser - Fatal编程技术网

Javascript 从孩子们只知道父母的文档中获取ID列表

Javascript 从孩子们只知道父母的文档中获取ID列表,javascript,json,browser,Javascript,Json,Browser,所以我有一个来自CouchDB的数据结构 [ { id: '1', type: 'bot', }, { id: '2', type: 'conversation', owner: '1', // bot id 1 }, { id: '3', type: 'message', owner: '2', // conversation id 2 }, { id: '4', type: 'message', owner: '

所以我有一个来自CouchDB的数据结构

[
 {
   id: '1',
   type: 'bot',
 },
 {
   id: '2',
   type: 'conversation',
   owner: '1', // bot id 1
 },
 {
   id: '3',
   type: 'message',
   owner: '2', // conversation id 2
 },
 {
   id: '4',
   type: 'message',
   owner: '2', // conversation id 2
 },
 {
   id: '5',
   type: 'conversation',
   owner: '1', // bot id 1
 },
 {
   id: '6',
   type: 'bot',
 },
 {
   id: '7',
   type: 'conversation',
   owner: '6', // bot id 6
 },
 {...}
]
我正在尝试获取一个启动潜在家长的ID列表。父id可以是会话id(拥有消息),也可以是机器人id(拥有会话和消息)

因此,基于上述数据,如果我提供id
1
(在本例中为bot),预期结果将是
[2,3,4,5]

我正在尝试使用vanilla JS完成这项工作。我之所以避免递归,是因为浏览器中缺少尾部调用优化


谢谢大家!

您可以使用双过程方法(稍后使用递归)。首先收集所有孩子并将其分配给父母,然后获取所有孩子

函数getChildren(数组,id){ 功能iter(id){ 结果:推送(id); (儿童[id]| |[])forEach(国际热核实验堆); } var children=Object.create(null), 结果=[]; array.forEach(函数(o){ if(o中的“所有者”){ 儿童[o.owner]=儿童[o.owner]| |[]; 子项[o.owner]。推送(o.id); } }), 国际热核实验堆; 返回结果。切片(1);//不带起始id } var data=[{id:'1',type:'bot'},{id:'2',type:'conversation',owner:'1'},{id:'3',type:'message',owner:'4',type:'message',owner:'2'},{id:'conversation',owner:'1'},{id:'6',type:'bot id:'7',type:'conversation',owner:'6'};
log(getChildren(数据“1”)
'7'
呢?@NinaScholz对不起,那是个打字错误,我已经修好了<代码>7属于
6