Last active
August 24, 2023 15:46
-
-
Save vegadelalyra/af98fcffba2b0d21d4efe8a75f4f9f52 to your computer and use it in GitHub Desktop.
Flatten Object Functions
This file contains hidden or 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
// Export from your streaming service like Spotify, YT music, etc. | |
const artistsByGenre = { | |
jazz: ['Miles Davis', 'John Coltrane'], | |
rock: { | |
classic: ['Bob Seger', 'The Eagles'], | |
hair: ['Def Leppard', 'Whitesnake', 'Poison'], | |
alt: { | |
classic: ['Pearl Jam', 'The Killers'], | |
current: ['Joywave', 'Sir Sly'] | |
} | |
}, | |
unclassified: { | |
new: ['Caamp', 'Neil Young'], | |
classic: ['Seal', 'Morcheeba', 'Chris Stapleton'] | |
} | |
} | |
const getArtistNames = (dataObject, array = []) => { | |
Object.keys(dataObject).forEach(key => { | |
if (Array.isArray(dataObject[key])) { | |
return dataObject[key] | |
.forEach(artist => array.push(artist)) | |
} | |
getArtistNames(dataObject[key], array) | |
}) | |
return array | |
} | |
console.log(getArtistNames(artistsByGenre).join('\n')) |
This file contains hidden or 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 flatObject(nestedObject, parentKey = '') { | |
let flattenedObject = {} | |
Object.entries(nestedObject).map(([key, value]) => { | |
const newKey = parentKey ? parentKey + '_' + key : key | |
if (typeof value != 'object') return flattenedObject[newKey] = value | |
const objectValueFlattened = flatObject(value, newKey) | |
flattenedObject = { ...flattenedObject, ...objectValueFlattened} | |
}) | |
return flattenedObject | |
} |
Author
vegadelalyra
commented
Aug 24, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment