Last active
August 29, 2015 14:25
-
-
Save matfin/4160e98141eaa6029303 to your computer and use it in GitHub Desktop.
A simple solution to convert an object map into an array
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
'use strict'; | |
/** | |
* Given an object map like this one | |
*/ | |
var map = { | |
objectOne: { | |
attributeOne: 1, | |
attributeTwo: 2 | |
}, | |
objectTwo: { | |
attributeOne: 3, | |
attributeTwo: 4 | |
}, | |
objectThree: { | |
attributeOne: 5, | |
attributeTwo: 6 | |
} | |
}; | |
var objToArray = function(obj) { | |
var array = [], | |
keys = Object.keys(obj), | |
item; | |
keys.forEach(function(key) { | |
item = obj[key]; | |
array.push({ | |
name: key, | |
attributes: item | |
}); | |
}); | |
return array; | |
}; | |
/** | |
* The following function call should show this | |
* | |
* [ | |
{ | |
name: 'objectOne', | |
attributes: { attributeOne: 1, attributeTwo: 2 } | |
}, | |
{ | |
name: 'objectTwo', | |
attributes: { attributeOne: 3, attributeTwo: 4 } | |
}, | |
{ | |
name: 'objectThree', | |
attributes: { attributeOne: 5, attributeTwo: 6 } | |
} | |
] | |
*/ | |
console.log(objToArray(map)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment