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 id
s 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.