Sometimes, we want to convert a JavaScript object into a key-value object array.
In this article, we’ll look at how to convert a JavaScript object into a key-value object array.
Convert a JavaScript Object into a Key-Value Object Array
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.
For instance, we write:
const data = {
firstName: 'John',
lastName: 'Doe',
email: '[email protected]'
}
const output = Object.entries(data).map(([key, value]) => ({
key,
value
}));
console.log(output);
to call Object.entries
with data
to return an array of key-value pair arrays in the data
object.
Then we call map
with a callback that destructures the key
and value
from the parameter, put them in an object as properties, and then return the object.
Therefore, output
is:
[
{
"key": "firstName",
"value": "John"
},
{
"key": "lastName",
"value": "Doe"
},
{
"key": "email",
"value": "[email protected]"
}
]
according to the console log.
Conclusion
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.