How to convert an Object {} to an Array [] of key-value pairs in JavaScript?
Last Updated :
15 Dec, 2023
The task is to convert an Object {} to an Array [] of key-value pairs using JavaScript.
Objects in JavaScript are the most important data type and form the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data types (Number, String, Boolean, null, undefined, and symbol). Objects are more complex and each object may contain any combination of these primitive data types as well as reference data types, while the array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.
Methods to convert the Objects to JavaScript Array:
- In this method, we will use Object.keys() and map() to achieve this.
- By using Object.keys(), we are extracting keys from the Object then this key is passed to the map() function which maps the key and corresponding value as an array.
Syntax:
Object.keys(obj);
Parameters:
- obj: It is the object whose enumerable properties are to be returned.
Syntax:
map(function callback(currentValue[, index[, array]]){
// Return element for new_array
}
Parameter:
- callback: Function that produces an element of the new Array
Example: In this example, a JavaScript object will be converted to an array using the Object.keys() and map() methods.
javascript
let obj = { "1" : 5, "2" : 7, "3" : 0, "4" : 0, "5" : 0 };
let result = Object.keys(obj).map( function (key) {
return [Number(key), obj[key]];
});
for (let i = 0; i < result.length; i++) {
for (let z = 0; z < result[i].length; z++) {
console.log(result[i][z]);
}
}
|
Output
1
5
2
7
3
0
4
0
5
0
We will use Object.entries() which is available in JavaScript. Object.entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter. The ordering of the properties is the same as that given by looping over the property values of the object manually.
Syntax:
Object.entries(obj);
Parameters:
- obj: It is the object whose enumerable own property [key, value] pairs are to be returned.
Example: In this example, a javascript object will be converted to a javascript array using the Object.entries() method.
javascript
let obj = {
"1" : 500,
"2" : 15,
"5" : 4,
"4" : 480,
"10" : 87
};
let result = Object.entries(obj);
for (let i = 0; i < result.length; i++) {
for (let z = 0; z < result[i].length; z++) {
console.log(result[i][z]);
}
}
|
Output
1
500
2
15
4
480
5
4
10
87
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...