-2
var object = 
{ 
  'a':  
  { 
 'b': { 'ba': {}, 'bb': {}, 'bc': {}, 'bd': {} },
 'c: { 'ca': {}, 'cb': {}, 'cc': {} },
 'd': {},
 'e': { 'ea': {}, 'eb': {}, 'ec: {}, 'ed': {}, 'ef': {} },
 'f: {},
 'g': {},
 'h': {} 
 },

 'aa':   
 { 
 'bb': { 'bba': {},  'bbb': {},''bbc': {},'bbd': {},'bbe': {},  
 'bbf': {}, 'bbg': {} },
 'cc': {},
 'dd': { 'dda': {}, 'ddb': {}, 'ddc': {} },
 'ee': {},
 'ff': {} 
 },

}

I want to convert to like this

['a b ba'] ['a b bb'] ['a b bc'] ['a b bd']
['a c ca'] ['a c cb'] ['a c cc']['a d'] 
['a e ea'] ['a e eb'] ['a e ec'] ['a e ed'] ['a e ef']
['a f']['a g']['a h']
['aa bb bba'] ['aa bb bbb'] ['aa bb bbc'] ['aa bb bbd'] ['aa bb bbf'] 
['aa bb bbg']
['aa cc']['aa dd dda'] ['aa dd ddb'] ['aa dd ddc']['aa ee']['aa ff']

only javascript.. it is possible convert ??

I guess use repeat for and hasOwnproperty.

If it doesn't work like that, I want to change it to an array.

help.

  • 4
    your object has some syntax error, some of the brackets are not properly closing. Can you update the object with properly – Learner Dec 12 '18 at 14:51
  • possible duplicate from https://stackoverflow.com/questions/20881213/converting-javascript-object-with-numeric-keys-into-array – Nicolo Lüscher Dec 12 '18 at 14:55

1 Answers1

1

You'll need to loop over your object's nested key structures recursively.

You can check if you're at the end of a branch by using Object.keys. If there are no keys, we can return.

You can loop over a node's branches by using Object.entries

By using concat we keep adding branches to our flat result array until we've looked at every node in the tree.

var object={a:{b:{ba:{},bb:{},bc:{},bd:{}},c:{ca:{},cb:{},cc:{}},d:{},e:{ea:{},eb:{},ec:{},ed:{},ef:{}},f:{},g:{},h:{}},aa:{bb:{bba:{},bbb:{},bbc:{},bbd:{},bbe:{},bbf:{},bbg:{}},cc:{},dd:{dda:{},ddb:{},ddc:{}},ee:{},ff:{}}};

var keyPaths = (obj, path = [], paths = []) => 
  Object.keys(obj).length === 0
    ? paths.concat(path.join(" "))
    : Object.entries(obj)
            .reduce(
              (ps, [k, v]) => keyPaths(v, path.concat(k), ps),
              paths
            );
            
            
console.log(keyPaths(object));
    
user3297291
  • 22,592
  • 4
  • 29
  • 45