If we have object like this
var x = {foo:1}
x.bar = x
We can't send it over http, because of circular reference. We also can't stringify it. Another problem we may have multiple references to same object. Like this:
var palette1 = {red:'red',green:'green',blue:'blue'}
var palette2 = {red:'red',green:'green',blue:'blue'}
var data = {
rows: [
{ id:0, ..., palette: palette1},
{ id:1, ..., palette: palette2},
{ id:2, ..., palette: palette1},
{ id:3, ..., palette: palette2}
...
]
}
If we'll do JSON.stringify(data)
- it will return long string, but actually a lot of data is repeated.
More then that, if we'll do data = JSON.parse(JSON.stringify(data))
- we will have many instances of palette1 & palette2.
Now if we'll change data.rows[0].palette.red = 'orange'
, 3rd item will still contain 'red' data.rows[2].palette.red === 'red'
To solve the problem, we may recursively traverse over the object and replace reused and circular references by some kind of link.
var reused = {foo:1, bar:2}
var x = {
a: reused,
b: reused
}
x.c = x
It will look like this:
{
a: {foo:1, bar:2},
b: '@root.a',
c: '@root'
}