javascript - 匹配对象数组中的 2 个属性的值并根据第三个属性的值过滤匹配项
问题描述
我有一个可以连接到多个其他节点的节点图。
每个节点代表一个数组中的一个对象。在每个节点的对象中都有一个数组,其中包含链接到该节点的所有节点的 id 及其深度:
nodes: [
{"id":1, "depth":0, "next":[], "children":[2, 3]}, // nodes.next = [2, 3]
{"id":2, "depth":1, "next":[], "children":[1, 4, 5]}, // nodes.next = [4, 5]
{"id":3, "depth":1, "next":[], "children":[1, 6, 7]}, // nodes.next = [6, 7]
{"id":4, "depth":2, "next":[], "children":[2, 8]}, // nodes.next = [8]
{"id":5, "depth":2, "next":[], "children":[2, 9]} // nodes.next = [9]
]
我想从某个节点遍历图形。
问题是节点的子数组包含链接到它的所有节点。深度为 2 的节点指向深度为 1 的节点。
所以我想在节点的对象中创建一个新数组,假设nodes.next
并摆脱指向深度低于自身的节点的子节点。
真正让我困惑的部分是检查nodes.children
. 我什至没有靠近我可能会检查节点深度nodes.children
是否高于nodes[i].depth
并推nodes[i].children[i]
到nodes[i].next
.
如果有更好的方法来解决这个问题,我很高兴知道。我的尝试在很多方面都没有结果:
let childDepth;
for (let i = 0; i < nodes.length; i++) {
for (let child in nodes[i].children) {
if (nodes.id === child) {
childDepth = nodes[i].depth;
}
if (childDepth > graph.nodes[i].depth) {
nodes[i].next.push(child)
}
}
}
更新数组:
const nodes = [
{ "id": 37, "depth": 0, "children": [210, 395, 265], "next": [] },
{ "id": 210, "depth": 1, "children": [37, 260, 259, 391],"next": [] },
{ "id": 256, "depth": 2, "children": [265], "next": [] },
{ "id": 259, "depth": 2, "children": [210, 397, 396], "next": [] },
{ "id": 260, "depth": 2, "children": [210], "next": [] },
{ "id": 265, "depth": 1, "children": [37, 256, 388, 394, 271, 269], "next": [] },
{ "id": 269, "depth": 2, "children": [265], "next": [] },
{ "id": 271, "depth": 2, "children": [265], "next": [] },
{ "id": 388, "depth": 2, "children": [265], "next": [] },
{ "id": 391, "depth": 2, "children": [210], "next": [] },
{ "id": 394, "depth": 2, "children": [265], "next": [] },
{ "id": 395, "depth": 1, "children": [37], "next": [] },
{ "id": 396, "depth": 3, "children": [259, 413], "next": [] },
{ "id": 397, "depth": 3, "children": [259], "next": [] },
{ "id": 413, "depth": 4, "children": [396], "next": [] }
];
解决方案
请看看下面的代码,看看它是否是你要找的
const array = [
{id:1, depth:0, next:[], children:[2, 3]},
{id:2, depth:1, next:[], children:[1, 4, 5]},
{id:3, depth:1, next:[], children:[1, 6, 7]},
{id:4, depth:2, next:[], children:[2, 8]},
{id:5, depth:2, next:[], children:[2, 9]}
]
array.forEach(x => {
let { children, depth } = x;
for(let i=depth; i< children.length; i++){
x.next.push(children[i]);
}
});
输出如下:
[
{"id":1,"depth":0,"next":[2,3],"children":[2,3]},
{"id":2,"depth":1,"next":[4,5],"children":[1,4,5]},
{"id":3,"depth":1,"next":[6,7],"children":[1,6,7]},
{"id":4,"depth":2,"next":[],"children":[2,8]},
{"id":5,"depth":2,"next":[],"children":[2,9]}
]
推荐阅读
- java - 如何在处理中旋转和振荡同一个对象
- c# - 由于 Entity 中的“必需”导航属性,ModelState.IsValid 为 false
- c++ - 拥有一个不使用 Qt 类但使用 Qt 视图的模型是否可行?
- sql - 如何使用 >=all 找到最大值?
- reactjs - NGINX 和反应 :net::ERR_ABORTED 404
- ios - Spotify 会话更新问题
- python - 互斥组中的 Python argparse 帮助选项
- ios - 具有数据 URI 和下载属性的锚点在 iOS/Safari 中不起作用
- angular - doc.fromHTML 不是 angular 6 的函数
- css - 我在 Laravel 中的哪里放置我的 css 文件?