Skip to content

Instantly share code, notes, and snippets.

@vegadelalyra
Last active August 24, 2023 15:46
Show Gist options
  • Save vegadelalyra/af98fcffba2b0d21d4efe8a75f4f9f52 to your computer and use it in GitHub Desktop.
Save vegadelalyra/af98fcffba2b0d21d4efe8a75f4f9f52 to your computer and use it in GitHub Desktop.
Flatten Object Functions
// 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'))
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
}
@vegadelalyra
Copy link
Author

image

@vegadelalyra
Copy link
Author

Two versions: With former you will get an array as return, with latter you will get a json. Choose according to your logic needs.
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment