Skip to content

Instantly share code, notes, and snippets.

@matfin
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matfin/4160e98141eaa6029303 to your computer and use it in GitHub Desktop.
Save matfin/4160e98141eaa6029303 to your computer and use it in GitHub Desktop.
A simple solution to convert an object map into an array
'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