Skip to content

Instantly share code, notes, and snippets.

@srph
Created October 16, 2018 05:11
Show Gist options
  • Save srph/53ed4fde34d7a29d26316f2767c4a7c0 to your computer and use it in GitHub Desktop.
Save srph/53ed4fde34d7a29d26316f2767c4a7c0 to your computer and use it in GitHub Desktop.
JS: Array-like data structure to array
function obj2arr(obj) {
var arr = []
function flatten (subobj, isRoot) {
var result = {}
Object.keys(subobj).forEach(key => {
if (typeof subobj[key] === 'object') {
flatten(subobj[key], false)
} else {
result[key] = subobj[key]
}
})
if (!isRoot) {
arr.push(result)
}
}
flatten(obj, true)
return arr
}
obj2arr(
{
justin: {
lastname: "lazaro",
age: 10
},
eon: {
lastname: "musk",
age: 20,
jeffy: {
lastname: "musdsadask",
age: 19
}
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment