Rob Brander Rob Brander - 5 months ago 20
Javascript Question

How to transpose a javascript object into a key/value array

Given a JavaScript object, how can I convert it into an array of objects (each with key, value)?

Example:

var data = { firstName: 'John', lastName: 'Doe', email: 'john.doe@gmail.com' }


resulting like:

[
{ key: 'firstName', value: 'John' },
{ key: 'lastName', value: 'Doe' },
{ key: 'email', value: 'john.doe@gmail.com' }
]

Answer

You can just iterate over the object's properties and create a new object for each of them.

var data = { firstName: 'John', lastName: 'Doe', email: 'john.doe@gmail.com' };
var result = [];

for(var key in data)
{
    if(data.hasOwnProperty(key))
    {
        result.push({
            key: key,
            value: data[key]
        });
    }
}
Comments