Skip to content

Instantly share code, notes, and snippets.

@SergioR82
Last active November 13, 2018 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergioR82/6d5c55df236ba5ac33682edb8433933c to your computer and use it in GitHub Desktop.
Save SergioR82/6d5c55df236ba5ac33682edb8433933c to your computer and use it in GitHub Desktop.
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