Rob Brander Rob Brander - 1 year ago 97
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)?


var data = { firstName: 'John', lastName: 'Doe', email: '' }

resulting like:

{ key: 'firstName', value: 'John' },
{ key: 'lastName', value: 'Doe' },
{ key: 'email', value: '' }

Answer Source

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: '' };
var result = [];

for(var key in data)
            key: key,
            value: data[key]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download