Object to Array

There are lots of things that you can do with arrays in JavaScript that you can't do with objects. While you can use an array like notation to reference the properties of objects you can't use any of the array methods on those objects.

The simplest solution to this is to convert the object to an array so that we can then use array methods for processing our object properties. The problem is that object properties have both a name for the property and a value whereas arrays only have values (the names effectively being 0, 1, 2 through as many entries as are in the array).

This too has a solution if we make each entry of the array an array that itself consists of two entries so as to hold the name and the value together. Of course having used the array methods we then need to be able to convert the result back into an object again.

The following two functions do this for us. The first function turns an object into an array where each entry in that array is an array containing both the name and value of the property. The second function takes an array that consists of arrays of name value pairs and converts it into an object.

function convertObjToArray(obj) {
return Object.keys(obj).map(function (key) {return [key,obj[key]];});
function convertArrayToObj(ary) {
var obj = {};
ary.forEach(function(a) {obj[a[0]]=a[1];});
return obj;

The following example illustrates how this works:

var a = {x:5,y:4};
console.log(a); // {x: 5,y: 4}
b = convertObjToArray(a);
console.log(b); // [["x", 5], ["y", 4]]
c = convertArrayToObj(b);
console.log(c); // {x: 5,y: 4}


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow