Last active
November 13, 2018 02:22
-
-
Save SergioR82/6d5c55df236ba5ac33682edb8433933c to your computer and use it in GitHub Desktop.
Traverse an array of objects using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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