Search code examples
javascriptarraysjavascript-objects

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: '[email protected]' }

resulting like:

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

Solution

  • var data = { firstName: 'John', lastName: 'Doe', email: '[email protected]' }
    var output = Object.entries(data).map(([key, value]) => ({key,value}));
    
    console.log(output);

    Inspired By this post