Javascript serialization

Do I have the ability to serialize meta (any format, so I can save it to the database)?

var obj1 = {};
var obj2 = {};
obj1.link = obj2;
obj2.link = obj1;
var meta = [obj1, obj2];

As I understand it, the problem is that JSON serializes references to object objects.

+3
source share
3 answers

Yes. You will need to provide your objects with a kind of identifier and use it as a reference.

var obj1 = {id: "obj1"};
var obj2 = {id: "obj2"};
obj1.link = "obj2";
obj2.link = "obj1";
var meta = [obj1, obj2];
+2
source

One approach is to use the object as the outermost container, using the keys of the object as identifiers:

var objs = { 
   obj1: { link: "obj2" }, 
   obj2: { link: "obj1" } 
}

Then you can only follow links with property searches:

var o1 = objs["obj1"];
var o2 = objs[o1.link];

And this will convert to JSON without any conversion

+1
source

JSON- :

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"}'
+1

Source: https://habr.com/ru/post/1744362/


All Articles