serialize-to-js icon indicating copy to clipboard operation
serialize-to-js copied to clipboard

References in Map

Open EmileSonneveld opened this issue 5 years ago • 2 comments

Hi! This seems like a really promising library for debugging complex JS applications :) Or serialising complex JS objects.

In our code, we often use Map, but references in there get copied by value. Is there a way to generate JS code that will construct the full JS object?

var serialize = require('serialize-to-js')

var fooBar = {foo:"bar"}

let m = new Map()
m.set('key1', fooBar)
m.set('key2', fooBar)

var obj = {
  ref1: fooBar,
  ref2: fooBar,
  ref3: fooBar,
  m: m,
}

var opts = { reference: true }
var withoutRefs = serialize(obj, opts)
console.log(opts.references)

var refsCode = "var tmp = " + withoutRefs + ";\n"
for(var i = 0; i < opts.references.length; i+= 1){
    var entry = opts.references[i];
    refsCode += "tmp" + entry[0] + " = tmp" + entry[1] + ";\n"
}
console.log(refsCode)
// var tmp = {ref1: {foo: "bar"}}
// tmp.ref2 = tmp.ref1;
// tmp.ref3 = tmp.ref1;
// The refs in the map are missing :(

EmileSonneveld avatar Aug 01 '20 10:08 EmileSonneveld

Unfortunately I'm having troubles to correctly attribute the "references" within the Map. With objects the path naming conventions are clear using dots or brackets. With Map there is no such thing. Any thoughts?

commenthol avatar Aug 05 '20 19:08 commenthol

For me saving a complete JS object is the main goal. For me the ideal output of serialize(obj, opts) would be:

var obj = {
  ref1: {foo:"bar"},
  m: new Map(),
}
obj.ref2 = obj.ref1;
obj.ref3 = obj.ref1;
obj.m.set('key1', obj.ref1);
obj.m.set('key2', obj.ref2);

Only the first time an object is encountered, it is shown in the big tree. All other references are added latere on with separate statements.

EmileSonneveld avatar Aug 26 '20 16:08 EmileSonneveld