1

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']; 
1
  • You haven't defined what you expect as output. "Not working properly" does not help if "properly" is not defined. I can see that it simply returns the input destination value without assigning any properties or values to it. Commented May 24, 2016 at 2:16

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

typeof will never return array. for an array, it will return "object".
Thank you for pointing that out, I edited my response. Your answer is pretty slick. Stringify was my initial thought but I couldn't get it figured out quickly.
1

You could use side-effects of JSON.stringify to simplify your code.

function keysAndVals(object) { var result = []; JSON.stringify(object, function(key, val) { result.push(key); if (typeof val !== "object") result.push(val); return val; }); return result; } 

Comments