获取父元素及其所有子元素的数组

6 javascript arrays underscore.js lodash

假设我有这种数据......

data = [{
    "_id" : "1",
    "parentId" : "thisPostId",
    "topLevelId" : "1",
    "text" : "<p>comment</p>",
},
{
    "_id" : "2",
    "parentId" : "1",
    "topLevelId" : "1",
    "text" : "<p>reply to comment</p>",
},
{
    "_id" : "3",
    "parentId" : "2",
    "topLevelId" : "1",
    "text" : "<p>reply to reply to comment</p>",
},
{
    "_id" : "4",
    "parentId" : "3",
    "topLevelId" : "1",
    "text" : "<p>reply to reply to reply to comment</p>",
}]
Run Code Online (Sandbox Code Playgroud)

我需要删除评论及其所有孩子......

如果注释删除是_id:1,那么我需要一个数组["1","2","3","4"],,,然后我可以运行Coll.remove({_id:{$in:["1","2","3","4"]}}, callback);

如果注释要删除_id:2,那么我需要一个数组["2","3","4"]

如果注释要删除_id:3,那么我需要一个数组["3","4"]

如果注释要删除_id:4,那么我需要一个数组["4"]

我试过这个(不知道)......

_.forEach(data, function(value, key){
    _.pluck(_.where(key, { "parentId" : "2" }), '_id');
});
Run Code Online (Sandbox Code Playgroud)

并没有工作......

任何有关javascript/lodash/underscore的帮助将不胜感激,,,

谢谢...

Nin*_*olz 0

这是一个带有临时对象和 ids 递归调用的提案。

临时对象o包含所有 id 及其子对象

{
    "1": ["2"],
    "2": ["3"],
    "3": ["4"],
    "thisPostId": ["1"]
}
Run Code Online (Sandbox Code Playgroud)

构建此对象后,将获取用于查找的 id 并检查该对象是否包含该属性。虽然所有的对象都是数组,但可以迭代go()并获取所有 id 进行收集。如果还有另一个孩子,则递归迭代将继续。

{
    "1": ["2"],
    "2": ["3"],
    "3": ["4"],
    "thisPostId": ["1"]
}
Run Code Online (Sandbox Code Playgroud)