gpt4 book ai didi

javascript - 匹配对象数组中的 2 个属性值,并根据第三个属性值过滤匹配

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:10:17 24 4
gpt4 key购买 nike

我有一个图表,其中的节点可以连接到多个其他节点。

每个节点代表数组中的一个对象。在每个节点的对象中都有一个数组,其中包含链接到该节点的所有节点的 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": [] }
];

enter image description here

最佳答案

请看下面的代码,看看它是否是您要找的东西

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]}
]

关于javascript - 匹配对象数组中的 2 个属性值,并根据第三个属性值过滤匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50441529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com