Answer the question
In order to leave comments, you need to log in
How to turn objects with links into JSON?
Good afternoon, How to turn objects with links into JSON?
But without using a third party library?
Turn the team object from the example below into JSON:
var leader = {
name: "Василий Иванович"
};
var soldier = {
name: "Петька"
};
// эти объекты ссылаются друг на друга!
leader.soldier = soldier;
soldier.leader = leader;
var team = [leader, soldier];
Answer the question
In order to leave comments, you need to log in
The point is that JSON cannot have circular references by definition. It doesn't even have variables.
Your best bet is to switch to a slightly different data format. Namely, to store not references to objects, but their keys as strings . Such reference strings are easily serialized.
leader.soldier = "soldier";
soldier.leader = "leader";
for (let key in obj) {
if (window[key]) obj[key] = key; //любой ваш критерий
}
var test_leader = soldier.leader && window[soldier.leader];
//Конечно, вместо window у вас будет свой объект-обертка
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question