Created
November 17, 2018 22:52
-
-
Save SergioR82/408c3e4c0dd3ffb5243c7ad531f025ad to your computer and use it in GitHub Desktop.
Traverse with straight loop and 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
function TraverseHybrid(bookarray, resultArray = [], currentObj = {}){ | |
//Safe case when bookarray is not an array. | |
if (!Array.isArray(bookarray)) return resultArray; | |
//Safe case when bookarray is empty. | |
if (bookarray.length <= 0) return resultArray.push(currentObj); | |
let resultObj = {}; | |
let data = {}; | |
let hasPropArray = false; | |
for(let pos = 0; pos < bookarray.length; pos++){ | |
if (typeof bookarray[pos] === 'object' && !(isObjectEmpty(bookarray[pos]))){ | |
data = bookarray[pos]; | |
for (let property in data) { | |
if (data.hasOwnProperty(property)) { | |
if (isPrimitive(data[property])) | |
resultObj[property] = data[property]; | |
else | |
if (Array.isArray(data[property])){ | |
hasPropArray = true; | |
TraverseHybrid(data[property], resultArray, resultObj); | |
}; | |
}; | |
}; | |
if (!hasPropArray) resultArray.push(Object.assign({},currentObj,resultObj)); | |
} | |
else { | |
//Safe case when bookarray is empty. | |
return resultArray.push(currentObj); | |
}; | |
hasPropArray = false; | |
}; | |
return resultArray; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment