用于在Javascript中表示DAG的数据结构 [英] Data Structure to represent a DAG in Javascript

查看:436
本文介绍了用于在Javascript中表示DAG的数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我需要使用javascript解析为图形(DAG)数据结构。数据结构中包含我应该存储的一些属性,例如节点的id,名称以及如果链接存在于另一个节点,则给予该链接的标签。所以,一个例子是

I have a string that I need to parse into a graph (DAG) data structure using javascript. Included in the data structure are a few attributes I should store, such as the node's id, name, and a label that is given to the link if one exists to another node. So, an example would be

Node1 (id: 1, name: 'first') --('link name')--> Node2 (id:....)

等等。一旦创建了数据结构,除了读取它之外,我不需要再对它进行任何操作(稍后我将使用它来渲染d3的可视化)。节点的数量不会很多,因为它们中的一些是共享的。

and so forth. Once the data structure is created I do not need to do any more operations on it other than read it (I will later use it to render a visualization with d3). The amount of nodes will not be very many, as several of them are shared.

我想象一个邻接列表,但我不确定如何在javascript中对其进行编码。例如,我知道一个json对象可以有一个field:value结构,但我可以用Object:[相邻对象列表]吗?

I am imagining an adjacency list but am not sure how I would encode that in javascript. For instance, I know a json object can have a "field" : "value" structure but can I do that with Object : [list of adjacent Objects]?

推荐答案

你可以在json中使用列表(数组)。例如。我可以将一个简单的有向图表示为

you can use lists (arrays) in json. E.g. I could represent a simple directed graph as

{
  "NodeA": {"name": "NodeA", "adjacentTo": ["NodeB", "NodeC"]},
  "NodeB": {"name": "NodeB", "adjacentTo": ["NodeC", "NodeD"]},
  "NodeC": {"name": "NodeC", "adjacentTo": ["NodeA"]},
  "NodeD": {"name": "NodeD", "adjacentTo": []}
}

这将是图表:

C
^^
| \
|  \
A -> B -> D

名称字段确实不需要,但您可以将所需的任何属性与节点相关联那样。

The name field really isn't needed, but you can associate any attributes you want with a node that way.

这篇关于用于在Javascript中表示DAG的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆