如何将含parentId的扁平评论数组转为树形结构?修复空数组问题
扁平评论数组转树形结构问题修复
你当前的代码在处理parentId为null的顶级评论时返回空数组,问题出在filter的判断逻辑上:当item[link]是null时,三元表达式直接返回false,导致所有顶级评论被过滤掉,最终返回空数组。
示例数据
{"comments": [{"body": "asdf","createdAt": "2022-11-15T17:53:05.048Z","createdBy": {"id": "user:34nrxg022jt61t3xecgx","username": "asdf"},"id": "comments:fmd0noccuj","parentId": "comments:yxbc3jv4yp","postId": "posts:j6uzaypl61","updatedAt": "2022-11-15T17:53:05.048Z"},{"body": "asdf","createdAt": "2022-11-15T17:51:36.154Z","createdBy": {"id": "user:34nrxg022jt61t3xecgx","username": "asdf"},"id": "comments:gfanwk4r1d","parentId": null,"postId": "posts:j6uzaypl61","updatedAt": "2022-11-15T17:51:36.154Z"},{"body": {},"createdAt": "2022-11-15T17:48:38.321Z","createdBy": {"id": "user:34nrxg022jt61t3xecgx","username": "asdf"},"id": "comments:0atvept3ob","parentId": null,"postId": "posts:j6uzaypl61","updatedAt": "2022-11-15T17:48:38.321Z"},{"body": {},"createdAt": "2022-11-15T17:45:45.008Z","createdBy": {"id": "user:34nrxg022jt61t3xecgx","username": "asdf"},"id": "comments:kiqco3uexk","parentId": null,"postId": "posts:j6uzaypl61","updatedAt": "2022-11-15T17:45:45.008Z"},{"body": {},"createdAt": "2022-11-15T17:44:34.587Z","createdBy": {"id": "user:34nrxg022jt61t3xecgx","username": "asdf"},"id": "comments:gs641tos5h","parentId": null,"postId": "posts:j6uzaypl61","updatedAt": "2022-11-15T17:44:34.587Z"},{"body": "Test2","createdAt": "2022-11-15T10:14:24.119Z","createdBy": {"id": "user:34nrxg022jt61t3xecgx","username": "asdf"},"id": "comments:yxbc3jv4yp","parentId": null,"postId": "posts:j6uzaypl61","updatedAt": "2022-11-15T10:14:24.119Z"},{"body": "test","createdAt": "2022-11-15T10:09:13.370Z","createdBy": {"id": "user:34nrxg022jt61t3xecgx","username": "asdf"},"id": "comments:1llogp6a7t","parentId": null,"postId": "posts:j6uzaypl61","updatedAt": "2022-11-15T10:09:13.370Z"},{"body": "test","createdAt": "2022-11-15T10:07:22.243Z","createdBy": {"id": "user:34nrxg022jt61t3xecgx","username": "asdf"},"id": "comments:xqrk9bfp0h","parentId": null,"postId": "posts:j6uzaypl61","updatedAt": "2022-11-15T10:07:22.243Z"}]}
问题代码
const data = await res.json(); const nest = (items, id = null, link = 'parentId') => items .filter((item) => (item[link] ? item[link] === id : false)) .map((item) => ({ ...item, children: nest(items, item.id) })); this.comments = nest(data.comments);
修复方案
直接修改filter的判断条件,去掉多余的三元表达式,直接用全等比较item[link] === id——因为null === null会返回true,刚好匹配顶级评论的parentId,同时也能正确匹配子评论的parentId与父节点id:
const data = await res.json(); const nest = (items, id = null, link = 'parentId') => items .filter(item => item[link] === id) .map(item => ({ ...item, children: nest(items, item.id) })); this.comments = nest(data.comments);
修复后,顶级评论会被正确筛选出来,子评论也会被挂载到对应的父节点下,生成完整的树形评论结构。
内容的提问来源于stack exchange,提问作者chovy
相关产品推荐
相关产品推荐

