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]' } ]
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.
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
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, ...
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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With