javascript - 从数组中查找父母和孩子
问题描述
在下面的数组中,一些项目是父项,其中一些是其子项。
我想找到父母(深度为0)和他们的孩子(嵌套深度为1-深度2-深度3),然后推送到另一个数组。
到目前为止,我所做的仅适用于深度 0 和深度 1,不知道如何处理更多深度。
这是小提琴:http: //jsfiddle.net/s3x5f4ap/2/
const comments = [
{ "depth": 0,"id": "f35vz2f"},
{ "depth": 0,"id": "f359354"},
{ "depth": 1,"id": "f35e0b0", "parent_id": "f359354" },
{ "depth": 2, "id": "f35ji24", "parent_id": "f35e0b0"},
{ "depth": 2, "id": "f35rnwb", "parent_id": ""},
{ "depth": 2, "id": "f35ojh4", "parent_id": "f35e0b0" },
{ "depth": 3, "id": "f35lmch", "parent_id": "f35ji24"},
{ "depth": 3, "id": "f35kl96", "parent_id": "f35ji24"}]
const parent = comments.filter(cm => cm.depth == 0);
final = [];
final = parent;
comments.forEach(a => {
final.forEach(c => {
if (c.id == a.parent_id) {
c.child = []
c.child.push(a);
}
})
})
console.log(final)
解决方案
您可以收集节点的所有关系并构建一棵树。
var data = [{ depth: 0, id: "f35vz2f" }, { depth: 0, id: "f359354" }, { depth: 1, id: "f35e0b0", parent_id: "f359354" }, { depth: 2, id: "f35ji24", parent_id: "f35e0b0" }, { depth: 2, id: "f35rnwb", parent_id: "" }, { depth: 2, id: "f35ojh4", parent_id: "f35e0b0" }, { depth: 3, id: "f35lmch", parent_id: "f35ji24" }, { depth: 3, id: "f35kl96", parent_id: "f35ji24" }],
tree = function (data, root) {
var t = {};
data.forEach(o => {
Object.assign(t[o.id] = t[o.id] || {}, o);
t[o.parent_id] = t[o.parent_id] || {};
t[o.parent_id].children = t[o.parent_id].children || [];
t[o.parent_id].children.push(t[o.id]);
});
return t[root].children;
}(data, undefined);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- java - 如何在 Java 中解析这个 JSON?
- spring-boot - 在thymeleaf中单击按钮并调用url时增加会话属性
- mysql - 我必须显示不在“时间卡”表中的记录
- java - 在我的 Android 应用小部件中出现错误
- html - 在多个页面上批量编辑 HTML?
- apache-kafka - 无法在 Hyperledger Fabric 网络中设置 Kaka Orderers:意外的主题级元数据错误:kafka 服务器:复制因子无效
- javascript - 在 FullCalendar 中设置日期时出现弃用警告
- javascript - Slackbot:如何使用松弛通道功能
- python - 在 Python IDE 中使用 pgsql2shp 模块导出 shapefile
- javascript - MVC sql表数据转html表