Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]' } ] 
like image 897
Rob Brander Avatar asked Apr 04 '16 19:04

Rob Brander


People also ask

How do you convert an object to a key-value pair?

To convert a JavaScript object into a key-value object array, we can use the Object. entries method to return an array with of key-value pair arrays of a given object. Then we can use the JavaScript array map method to map the key-value pair arrays into objects.

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

How do you replace an object in an array of keys?

To change the key name in an array of objects with JavaScript, we use the array map method. const arrayOfObj = [ { key1: "value1", key2: "value2", }, { key1: "value1", key2: "value2", }, ]; const newArrayOfObj = arrayOfObj. map(({ key1: stroke, ... rest }) => ({ stroke, ...

Can object keys be arrays?

Description. Object. keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.


2 Answers

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

like image 143
atiq1589 Avatar answered Sep 23 '22 06:09

atiq1589


Using map function

var data = { firstName: 'John', lastName: 'Doe', email: '[email protected]' };    var result = Object.keys(data).map(key => ({ key, value: data[key] }));    console.log(result);      
like image 23
isvforall Avatar answered Sep 23 '22 06:09

isvforall