我试图找出最有效的方法来做到这一点。我有1个单一的对象,看起来像:使用2个数组的下划线嵌套子注释
var comments = [{
id: 1,
deleted: 0,
comment: 'I am the parent commenter',
created: 'Sun Mar 01 2014 18: 16: 53 GMT - 0800(PST)',
parent_id: null,
username: 'edmund'
}, {
id: 2,
deleted: 0,
comment: 'I am a reply',
created: 'Sun Mar 02 2014 18: 16: 59 GMT - 0800(PST)',
parent_id: 1,
username: 'sally'
}, {
id: 3,
deleted: 0,
comment: 'I'm also a reply',
created: 'Sun Mar 03 2014 18: 16: 59 GMT - 0800(PST)',
parent_id: 1,
username: 'susan'
}];
它包含的意见,如果评论有一个非空parent_id
,那么它是一个孩子。所以我分裂成这2个阵列,像这样:
var parents = [], children = [];
_(comments).filter(function(comment) {
comment.parent_id === null ? parents.push(comment) : children.push(comment);
});
那么什么是追加所有儿童特定父评论的最佳方式?我想是这样的:
children.forEach(function(child) {
parents[child['parent_id']]['children'] = _.where(children, { parent_id : child.parent_id });
});
有没有一种方法,我可以将所有的这些
可孩子也是父母? –
@TedHopp孩子永远不会是父母(我只能嵌套一层)。 –
@bob_cobb你的目标是做树评论列表,不是吗? – Evgeniy