javascript - 显示嵌套数组项反应原生
问题描述
我有很多评论和他们的回复,如下所示:
[
{
commentId: "5efd85d5b2eff7063b8ec802",
description: "some comment description",
isAnonymous: false,
createdAt: "2020-07-02T06:59:33.317Z",
currentUserLiked: 0,
likes: 0,
user: {
firstName: "ar",
lastName: "ar",
email: "test@email.com",
username: "sami",
isVerified: false,
},
children: [
{
commentId: "5efd86b7b2eff7063b8ec803",
parentId: "5efd85d5b2eff7063b8ec802",
description: "some comment description",
isAnonymous: false,
createdAt: "2020-07-02T07:03:19.405Z",
currentUserLiked: 0,
likes: 0,
user: {
firstName: "ar",
lastName: "ar",
email: "test@email.com",
username: "sami",
isVerified: false,
},
children: [
{
commentId: "5efd89c4b2eff7063b8ec805",
parentId: "5efd86b7b2eff7063b8ec803",
description: "Child of Child",
isAnonymous: false,
createdAt: "2020-07-02T07:16:20.717Z",
currentUserLiked: 0,
likes: 0,
user: {
firstName: "ar",
lastName: "ar",
email: "test@email.com",
username: "sami",
isVerified: false,
},
children: [],
},
],
},
{
commentId: "5efd8996b2eff7063b8ec804",
parentId: "5efd85d5b2eff7063b8ec802",
description: "Child of Child",
isAnonymous: false,
createdAt: "2020-07-02T07:15:34.341Z",
currentUserLiked: 0,
likes: 0,
user: {
firstName: "ar",
lastName: "ar",
email: "test@email.com",
username: "sami",
isVerified: false,
},
children: [],
},
],
},
];
我想将它们显示为同一级别的所有孩子,以使用 flatList 进行本机反应。
我怎样才能做到这一点?
解决方案
我理解正确吗?:
const comments = [{id: 1, children: [{id: 2, children: [{id: 3, children:[]}]}]}];
const flatComments = (list) => {
return list.flatMap(el => {
const {children, ...out} = el;
return [out, ...flatComments(children)];
});
};
flatComments(comments);
// [{id: 1}, {id: 2}, {id: 3}];
推荐阅读
- visual-studio - 如何使用 SSRS 中的表达式获取前 2 个国家/地区的名称(基于它们在表中出现的次数)
- javascript - 使用 javascript get 方法从服务器恢复我的压缩文件
- azure - 在同一个应用服务计划实例上托管多个 Docker 映像实例
- rest - 无法在 Tableau 中查看数据源
- outlook - 对于测试 Office-js Outlook 加载项,是否存在针对所有不同常见最终用户目标的支持服务?[例如 Outlook 的浏览器截图?]
- c# - 如何提供 ILogger
来自.net核心控制器的新类对象中的实例? - jpa - 如何在实体 JPA 中指定外键
- c++ - CMake 无法设置 CUDA 标准 c++17
- postgresql - 访问排他锁原点
- terraform - Terraform 模板文件:错误:无法渲染:
:16,32-33:插值表达式后的额外字符;