Sometimes, we want to convert object’s properties and values to array of key value pairs with JavaScript.
In this article, we’ll look at how to convert object’s properties and values to array of key value pairs with JavaScript.
How to convert object’s properties and values to array of key value pairs with JavaScript?
To convert object’s properties and values to array of key value pairs with JavaScript, we can use the Object.entries
method.
For instance, we write:
const obj = {
value1: 'prop1',
value2: 'prop2',
value3: 'prop3'
};
const pairs = Object.entries(obj)
console.log(pairs)
We call Object.entries
with obj
to return an array of key-value arrays from the obj
object.
As a result, pairs
is:
[
[
"value1",
"prop1"
],
[
"value2",
"prop2"
],
[
"value3",
"prop3"
]
]
The first entry of each nested array is the key and the 2nd entry is the value of the corresponding key.
Conclusion
To convert object’s properties and values to array of key value pairs with JavaScript, we can use the Object.entries
method.