How to flatten deeply nested Array of Objects & Arrays [SOLVED]

Hi guys,

I thought this would be a pretty simple problem to solve, but I’m running in to some trouble flattening out an array of nested arrays and objects. I basically just want to flatten it out to one single array of values.

Basically, I want to check if any of the array properties are empty (so that includes everything in the objects and arrays that are nested). Perhaps there could be an easier way to go about this? My thought was to map over all the items and check for ‘’. But first I need to flatten the Array!

UPDATE:

Here’s what I did to get all the values from the array:

var flattenArray = function(data) {
	return data.reduce(function iter(r, a) {
		if (a === null) {
			return r;
		}
		if (Array.isArray(a)) {
			return a.reduce(iter, r);
		}
		if (typeof a === 'object') {
			return Object.keys(a).map(k => a[k]).reduce(iter, r);
		}
		return r.concat(a);
	}, []);
}
console.log(flattenArray(data))
1 Like

You can also use Array.prorotype.concat + apply to flatten multiple objects in an array.

[].concat.apply([], items.map(item => item.value)))