Skip to content

Instantly share code, notes, and snippets.

@andrIvash
Last active February 27, 2019 19:49
Show Gist options
  • Select an option

  • Save andrIvash/01d4f31867584051d41734ae82e2c816 to your computer and use it in GitHub Desktop.

Select an option

Save andrIvash/01d4f31867584051d41734ae82e2c816 to your computer and use it in GitHub Desktop.
getFiniteValue of nested objects with recursion and circular reference logging
// node.js version
var util = require('util');
var fractal = {
a1: {
b1: {
c: 1
},
b2: {
c: 222
},
b3: {
c: {
c: 33,
e: 2.5,
f: {
g: 9999,
h: {
i: {
c: 1001,
k: 'строка',
l: [1, 2, 3],
m: function () {}
}
}
}
}
}
}
};
fractal.a1.b2.m = fractal.a1.b2;
getFiniteValue(fractal);
console.log(util.inspect(fractal, false, null, true /* enable colors */));
function getFiniteValue (obj) {
var handledFlag = 'temp__isAlreadyHandled__';
getProp(obj);
function getProp (o, stack) {
var propertyPath;
for (var prop in o) {
if (typeof (o[prop]) === 'object') {
if (!o[prop][handledFlag]) {
Object.defineProperty(o[prop], handledFlag, {
value: true,
writable: false,
configurable: true
});
if (!stack) {
propertyPath = 'rootObject.' + prop;
} else {
propertyPath = stack + '.' + prop;
}
getProp(o[prop], propertyPath);
} else {
propertyPath = stack + '.' + prop;
console.log('Циклическая ссылка. Свойство: ' + propertyPath);
}
delete o[prop][handledFlag];
} else {
// console.log('Finite value: '+ o[prop]); log finite value
// change the finite object if the condition is met
if (prop === 'c') {
o.mduuid = 'ooooooooooo';
console.log('Finite value: ' + o[prop]);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment