views:

48

answers:

3

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.

+2  A: 

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];
RoToRa
A: 

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

Mark Bessey
+1  A: 

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"}'
Sean Kinsey