从儿童仅了解其父母的文档中获取ID列表

时间:2017-04-19 13:03:44

标签: 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: '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(在这种情况下是机器人),预期结果将是[2, 3, 4, 5]

我试图用vanilla JS完成这项工作。由于浏览器缺乏尾调用优化,我避免了递归。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用两遍方法(稍后使用递归)。首先收集并将所有孩子分配给他们的父母,然后让所有孩子。



function getChildren(array, id) {
    function iter(id) {
        result.push(id);
        (children[id] || []).forEach(iter);
    }

    var children = Object.create(null),
        result = [];

    array.forEach(function (o) {
        if ('owner' in o) {
            children[o.owner] = children[o.owner] || [];
            children[o.owner].push(o.id);
        }
    }),
    iter(id);
    return result.slice(1); // without starting id
}

var data = [{ id: '1', type: 'bot' }, { id: '2', type: 'conversation', owner: '1' }, { id: '3', type: 'message', owner: '2' }, { id: '4', type: 'message', owner: '2' }, { id: '5', type: 'conversation', owner: '1' }, { id: '6', type: 'bot' }, { id: '7', type: 'conversation', owner: '6' }];

console.log(getChildren(data, '1'));




相关问题