我試圖找出最有效的方法來做到這一點。我有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