我最近读了很多关于循环结构的文章,但我仍然想知道:
我如何字符串化
这样的对象:
var obj = {
thas: obj,
obj2: {
thos: obj.obj2
}
};
var jsonstring = JSON.stringify(obj);
alert(jsonstring);
来回,这样我什至可以从一开始就拥有字符串化版本并同样解析它。
最佳答案
我不知道您是否有机会更改对象层次结构,我建议您的问题采用不同的解决方案:
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--;
}
您提供 id
并通过 nextId
链接到下一个项目。解析该结构可能不需要其他信息。在运行时(浏览器或 Nodejs),您创建所需的对象结构。
我希望这个例子能有所帮助。
关于javascript - 使用 this 关键字来回转换循环结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34905819/