Fátima Alves Fátima Alves - 6 months ago 10
Javascript Question

Pushing keys and properties from object to array

I would like to push all properties and keys from objects, including nested ones. That's how i'm trying:



'use strict';

var getProps = function getProps(destination, object) {
destination = destination || [];
for (var key in object) {
typeof object[key] === 'object' && object[key] !== 'null'
? destination.push(getProps(destination, object[key]))
: destination.push(key);
}
return destination;
}

var object = {
one: {
two: 'three'
}
};


console.log(getProps([], object))





As you can see, isn't working properly.

Thanks in advance.

UPDATE -

Desire output:

['one', 'two', 'three'];

Answer

You could use recursion to achieve your desired result.

var object = {
	one: {
		two: 'three'
	},
  
        four: {
            five: 'six',
            seven: [
              'eight',
              'nine',
              'ten'
            ],
            eleven: {
              twelve: {
                thirteen: {
                   fourteen: 'fifteen'
                }
            }
        }
    }
};

function rabbitHole(output, object) {
   for (var i in object) {
     if (!Array.isArray(object)) {
         output.push(i);
     }
 
     if (typeof object[i] == 'object') {
         rabbitHole(output, object[i]);
     } else {
         output.push(object[i]);
     }
   }
   return output;
}

var output = rabbitHole([], object);

console.log(output);