Instantly share code, notes, and snippets.

@SergioR82 SergioR82/FlatBooks.js
Last active Nov 13, 2018

Embed
What would you like to do?
Traverse an array of objects using recursion
let isObjectEmpty = (obj) => {
return Object.keys(obj).length === 0;
};
let isPrimitive = (element) => {
return (typeof element === 'object') ? element === null : typeof element !== 'function';
};
function TraverseRecursiveArray (myarray, pos, obj){
if (!Array.isArray(myarray) || myarray.length <= 0) return [];
let hasPropArray = false;
let posSubArray = 0;
let resultObj = {};
let output = [];
if (pos === undefined) pos = 0;
if (typeof myarray[pos] === 'object' && !(isObjectEmpty(myarray[pos]))){
let data = myarray[pos];
for (var property in data) {
if (data.hasOwnProperty(property)) {
if (isPrimitive(data[property]))
resultObj[property] = data[property];
else
if (Array.isArray(data[property])){
hasPropArray = true;
// First recursive call to process a property array.
output.push(...TraverseRecursiveArray(data[property], posSubArray++, resultObj));
};
};
};
if (!hasPropArray)
output.push(Object.assign({},obj,resultObj));
}
if (pos < myarray.length-1)
//Second recursive call to process next item in current array.
output.push(...TraverseRecursiveArray(myarray,pos+1, obj));
return output;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment