下面是一个递归方法,用于从深度嵌套数组中删除注释。代码工作,但这里是我的问题:JS | lodash:从深层嵌套数组中递归删除
问题:
- 我使用_.remove循环中找到和当前的数组中删除注释。由于显而易见的原因,即循环内的循环似乎很昂贵,但其他方法似乎也是昂贵的。我相信有更好的方法来做到这一点。
工作示例:
https://plnkr.co/edit/PeW5ZFLynO2q8VNqbAHx?p=preview
var comments = [
{
id: 1,
depth: 0,
subject: 'Subject one'
},
{
id: 2,
depth: 0,
subject: 'Subject two',
children: [
{
id: 3,
depth: 1,
subject: 'Subject two dot one'
},
{
id: 4,
depth: 1,
subject: 'Subject two dot two'
}
]
},
{
id: 5,
depth: 0,
subject: 'Subject three',
children: [
{
id: 6,
depth: 1,
subject: 'Subject three dot one'
},
{
id: 7,
depth: 1,
subject: 'Subject three dot two',
children: [
{
id: 8,
depth: 2,
subject: 'Subject three dot two dot one'
},
{
id: 9,
depth: 2,
subject: 'Subject three dot two dot two'
}
]
}
]
}
];
function deleteComment(comment, comments) {
var self = this,
db = [];
function removeComment(items, parent) {
_.forEach(items, function (item) {
// QUESTION - seems expensive as we have a loop in a loop
_.remove(items, function(item) {
if (item.id === comment.id) {
console.log(item);
return true;
}
// NOTE: use above for demo purposes
// return item.id === comment.id
});
_.has(item, 'children') ? removeComment(item.children, item) : 0;
});
}
removeComment(comments, db);
}
var commentToBeDeleted = {
id: 8,
depth: 2,
subject: 'Subject three dot two dot one'
};
deleteComment(commentToBeDeleted, comments);
谢谢凯尔,我来看看,现在你提到它,我还会看看我是否可以用_.drop做些什么。值得注意的是,问题在于,随着应用程序越来越多地写入昂贵的/编写得差的代码片段,我开始堆积起来,结束了角度消化恶梦以及整体性能问题。 – Nolan