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

Rob Brander picture Rob Brander · Apr 4, 2016 · Viewed 50.5k times · Source

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]' }
]

Answer

atiq1589 picture atiq1589 · Apr 3, 2018

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