Dear Stack Overflow Community,
I have a question regarding object property replacement (you can skip to the bottom to read the question) . I'm working on an application, that gets a teacher object from the Back-end. The Back-end is using java hibernate to to a query of the database and serialize the object to be send to the front end (me). I get this teacher object, but there is circular references in the object. Which java handles by adding a reference id in place of the object. So i get this teacher object, and inside the object are these reference id's that i need to replace with the actual object, the problem being that they are nested objects. What i currently do is create a stack, and traverse the objects to find these id's and reference id's. When i find an id i put it on the stack. Not a problem, but when i find a reference id i need to repalce it with the one i found on the stack. Once again this is hard to do because i do these through a recursive function, so i don't have the physical object.
My question is, how can i replace nested object properties
var stack = {};
var add = function(prop, data) {
if (prop == '@id') {
stack[data[prop]] = data;
}
if (prop == '@ref') {
// console.log(stack[data[prop]])
// How do i replace the value with the stack object
// test.PROPERTY = stack[data[prop]] is what im looking for
}
}
var traverse = function(object) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
add(property, object);
if (object[property] && typeof object[property] === 'object') {
traverse(object[property]);
}
}
}
}
var test = {
'teacher': {
'course': {
"@id": "1",
'students': [{
"@id": "2",
'name': "John",
'course': {
"@ref": "1",
}
}, {
"@id": "2",
'name': "Next",
'course': {
"@ref": "1",
}
}]
}
}
};
setTimeout(() => {
console.log(stack);
// console.log(test);
}, 500);
traverse(test);