Julian Avar
Julian Avar

Reputation: 476

converting a circular structure back and forth with the this keyword

I've been reading a ton about circular structures lately, but I still wonder:

How would I stringify an object like this:

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

back and forth, so that I could even already have the stringified version from the beginning and parse it all the same.

Upvotes: 0

Views: 101

Answers (1)

Florian Salihovic
Florian Salihovic

Reputation: 3961

I don't know if you have any chance to change to object hierarchy, I'd suggest a different solution for your problem:

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

You provide ids and link to the next item via a nextId. There might be no other information needed to resolve the structure. At runtime (browser or Nodejs), you create the Object structure you need.

I hope this example helps a bit.

Upvotes: 1

Related Questions