【问题标题】:converting a circular structure back and forth with the this keyword使用 this 关键字来回转换循环结构
【发布时间】:2016-01-20 16:50:14
【问题描述】:

我最近阅读了大量有关圆形结构的文章,但我仍然想知道:

我如何stringify 这样的对象:

var obj = {
  thas: obj,
  obj2: {
    thos: obj.obj2
  }
};
var jsonstring = JSON.stringify(obj);
alert(jsonstring);

来回来回,这样我什至可以从一开始就拥有字符串化版本并对其进行同样的解析。

【问题讨论】:

标签: javascript json circular-reference


【解决方案1】:

我不知道您是否有机会更改对象层次结构,我会为您的问题提出不同的解决方案:

var str = "[{\"id\": 1, \"nextId\": 2}," +
           "{\"id\": 2, \"nextId\": 3}," +
           "{\"id\": 3, \"nextId\": 1}]",
    objects = JSON.parse(str),
    cache = {};

objects.forEach(function (o, i, arr) {
    cache[o.id] = o;
});

for (var key in cache) {
    var current = cache[key];
    var next = cache[cache[key].nextId];
    current.next = next;
    next.previous = current;
}

var item = objects[0], iterations = 10;

while (iterations) {
    console.log(item.id);
    item = item.next;
    iterations--;
}

您提供ids 并通过nextId 链接到下一个项目。解析结构可能不需要其他信息。在运行时(浏览器或 Nodejs),您创建所需的对象结构。

我希望这个例子有点帮助。

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2021-01-01
    • 2017-04-03
    相关资源
    最近更新 更多