[Edit]
+
0
-
0
JavaScript - JSON.stringify(object, replace, space) with full value path in replace() method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62// Source: https://dirask.com/snippets/js-check-if-value-is-object-jEZzx1 // const isObject = (entry) => { return entry === Object(entry); }; // Wraps JSON.stringify() method adding full path to value in replace() method. // const renderJson = (object, replace, space) => { let wrapper = null; if (replace) { const map = new Map(); wrapper = function(key, value) { // WARNING: do not change it to arrow function! if (value === object) { return replace([], value); } else { const item = map.get(this); const path = item ? [...item, key] : [key]; if (isObject(value)) { map.set(value, path); } return replace(path, value); } }; } return JSON.stringify(object, wrapper, space); }; // Usage example: const object = { owner: { id: 1, name: 'John' }, address: { id: 1, country: 'UK', city: 'London' } }; const replace = (keys, value) => { const path = keys.join('.'); // <------- `keys` is path to `value` (array of keys) console.log(` -> ${path}: ${value}`); return value; }; const json = renderJson(object, replace, 4); // Output: // // -> : [object Object] // -> owner: [object Object] // -> owner.id: 1 // -> owner.name: John // -> address: [object Object] // -> address.id: 1 // -> address.country: UK // -> address.city: London
Reset