Have I any chance to serialize meta (any format, so I can store it in DB)?
var obj1 = {};
var obj2 = {};
obj1.link = obj2;
obj2.link = obj1;
var meta = [obj1, obj2];
As I understand the problem is that JSON serialize object`s links to objects.
3 Answers 3
Yes. You'll need to give your objects some kind of ID and use that as a reference.
var obj1 = {id: "obj1"};
var obj2 = {id: "obj2"};
obj1.link = "obj2";
obj2.link = "obj1";
var meta = [obj1, obj2];
answered May 6, 2010 at 15:06
RoToRa
38.5k12 gold badges73 silver badges110 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
One approach is to use an object as the outermost container, using the keys of the object as the ids:
var objs = {
obj1: { link: "obj2" },
obj2: { link: "obj1" }
}
Then you can follow the links with just a property lookup:
var o1 = objs["obj1"];
var o2 = objs[o1.link];
And this converts to JSON without needing any conversions
answered May 6, 2010 at 15:17
Mark Bessey
19.8k4 gold badges51 silver badges70 bronze badges
Comments
JSON serializing such links can easily be avoided by using the replacer function:
var a = {}, b = {};
var d = {
a: a,
b: b,
c: "c"
};
JSON.stringify(d, function(key, value) {
if (value === a || value === b) {
return;
}
return value;
});
// returns '{"c":"c"}'
answered May 6, 2010 at 15:24
Sean Kinsey
38k7 gold badges55 silver badges71 bronze badges
Comments
lang-js