Hey guys in this article we will discuss how to convert Javascript objects into an array. There are scenarios where we need to convert a javascript object into an array and we can easily achieve that using Object class methods. Let’s discuss this in detail
Consider the following object –
let expense = {
name: 'Pay internet bill',
amount: 900.00,
category: 'Bills'
}
Let’s say we want to convert the object keys into an array, and this we can easily achieve using Object.keys()
Table of Contents
1. Object.keys()
Object.keys()
returns an array converting all the object properites to an array.
Object.keys(expense)
This will return an array
["name", "amount", "category"]
Let’s say i want to convert all the object values into an array, and we can achieve this using Object.values()
2. Object.values()
Object.values()
returns an array converting all the object values into an array.
Object.values(expense)
This will return an array with following output
["Pay internet bill", 900, "Bills"]
Let’s say we want both key and values to be converted into an array, then we can easily achieve this using Object.entries()
3. Object.entries()
Object.entries()
will return an array converting all the object key-value pairs into an array
Object.entries(expense)
This will return the following output
[["name", "Pay internet bill"], ["amount", 900], ["category", "Bills"]]