Skip to content

Instantly share code, notes, and snippets.

@TehShrike
Created November 8, 2014 23:20
Show Gist options
  • Save TehShrike/5ba1b17397589b761fe2 to your computer and use it in GitHub Desktop.
Save TehShrike/5ba1b17397589b761fe2 to your computer and use it in GitHub Desktop.
Parsing multiple objects from a single row
function getNames(key) {
var parts = key.split('_')
return {
type: parts.shift(),
property: parts.join('')
}
}
function rowToObjects(obj) {
var result = {}
Object.keys(obj).forEach(function(key) {
var names = getNames(key)
result[names.type] = result[names.type] || {}
result[names.type][names.property] = obj[key]
})
return result
}
var obj = {
butts_id: 13,
butts_name: 'lol',
user_id: 17,
user_name: 'Josh',
user_email: 'nope@fake.com'
}
console.log(rowToObjects(obj))
// { butts: { id: 13, name: 'lol' },
// user: { id: 17, name: 'Josh', email: 'nope@fake.com' } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment