Last active
February 27, 2019 19:49
-
-
Save andrIvash/01d4f31867584051d41734ae82e2c816 to your computer and use it in GitHub Desktop.
getFiniteValue of nested objects with recursion and circular reference logging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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