Member-only story
How To Convert Objects to Arrays and Vice Versa in JavaScript
Learn to use Object.entries() and Object.fromEntries()

If you’ve worked with data sets, especially web-based APIs, then I’m confident you have come across JavaScript Object Notation (JSON). A lightweight alternative to XML and the notation used in document-based databases such as MongoDB, JSON is everywhere.
This tutorial will demonstrate how to take an object and convert it to an array and vice versa using built-in methods in the Object
class. Before we get into that, let’s review JSON to make sure we’re clear on the basic syntax and what to expect when using the two conversion techniques.
JSON Overview
Two of the data types that make JSON so flexible are the Object and Array. These are complex data types that hold multiple values, as opposed to primitive data types that hold a single value.
- Objects are an unordered set of key-value pairs. The key is a text identifier that must be unique within the object and the value can be either a primitive or complex data value.
- Arrays are an ordered list of values that do not need to be unique and can be various data types. The position in the list is called an index, which is zero-based, meaning the first item in the array has an index of
0
.
Complex data sets may see arrays of objects or objects where a value is an array (or even another object). Any time you have a complex data structure within another, we refer to this as nesting.
Okay, now that we’ve done a one-minute primer on JSON, on to the solutions!
Converting an Object to an Array
When converting an object to an array, we’ll use the .entries()
method from the Object
class. This will convert our object to an array of arrays. Each nested array is a two-value list where the first item is the key and the second item is the value.
let character = {
"first_name": "Locke",
"last_name": "Cole",
"job": "Treasure Hunter"
}let arr = Object.entries(character);
console.log(arr);
/*
[
["first_name","Locke"],
["last_name","Cole"],
["job","Treasure Hunter"]
]
*/