javascript - Return array of string paths to every deep property within an object -


this question has answer here:

i have ugly 1mb+ json object numerous deep properties including nested arrays containing nested objects etc.

i'm looking function can return array of string "paths" every property in given object.

['obj.propa.first', 'obj.propa.second', 'obj.propb'] 

all of searching far has turned solutions going other direction. eg: taking path strings , fetching property values.

my gut says there has better way reinventing wheel.

thanks in advance!

example behavior:

var ugly = {   a: 'a',   b: ['b1', 'b2'],   c: {     c1: 'c1',     c2: ['c2a', 'c2b'],     c3: {       c3a: 'c3a',       c3b: [['c3b']],     },     c4: [{c4a: 'c4a'}],   } };  getpaths = function(obj) {       ??? };      getpaths(ugly) = [       'a',       'b[0]',       'b[1]',       'c.c1',       'c.c2[0]',       'c.c2[1]',       'c.c3.c3a',       'c.c3.c3b[0][0]',       'c.c4[0].c4a',     ]; 

this situation bit odd, , hint there problems @ architectural level, understand things inherited and/or unavoidable.

a bad mutable recursive implementation in node 4.2's version of es2015:

function isplainishobject(obj) {   return object.prototype.tostring.call(obj) === '[object object]'; }  function propinator (obj, _paths, _currentpath) {   _paths = _paths || [];    if (typeof obj !== 'object') {     _paths.push(_currentpath);   } else {     (let prop in obj) {       let path;       if (isplainishobject(obj)) {         path = _currentpath && `${_currentpath}.${prop}` || prop;       } else {         path = _currentpath && `${_currentpath}[${prop}]` || prop;       }        propinator(         obj[prop],         _paths,         path       );     }   }    return _paths; } 

tests:

let assert = require('assert'); assert.deepequal(propinator(ugly), [   'a',   'b[0]',   'b[1]',   'c.c1',   'c.c2[0]',   'c.c2[1]',   'c.c3.c3a',   'c.c3.c3b[0][0]',   'c.c4[0].c4a', ]);     

jsbin

this lightly tested (and poorly though out) opinions/improvements welcome.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -