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"]
]
*/
What about complicated objects that have nested objects and/or arrays? Only way to find out is to test!let obj = {
"name": "Rean Schwarzer",
"occupations": [
"Student (graduated)",
"Resistance Leader",
"New Class VII Instructor"
],
"parents": {
"father": "Teo",
"mother": "Lucia"
}
}let entries = Object.entries(obj);
console.log(entries);/*
[
["name", "Rean Schwarzer"],
[
"occupations", [
"Student (graduated)",
"Resistance Leader",
"New Class VII Instructor"
]
],
[
"parents", {
father: "Teo",
mother: "Lucia"
}
]
]
*/
Notice that the nested array or object simply becomes the second value in the appropriate two-item list. The method does not recursively convert the nested objects into arrays. Only the top-level is converted.
Convert an Array to an Object
Previously, converting from an object to an array was the only direction with built-in methods for the Object class. However as of ES2019/ES10, the .fromEntries() method was introduced, which converts an array of two-item arrays to an object—effectively the reverse of the .entries() method.
To see this in action, let’s start with a simple example. The result should be predictable.let scores = [
["Tim", 90],
["Joe", 88],
["Kelly", 95],
["Jesse", 77]
]let obj = Object.fromEntries(scores);
console.log(obj);
/*
{
Jesse: 77,
Joe: 88,
Kelly: 95,
Tim: 90
}
*/
Alright, now what about complex data?let arr = [
["name", "Rean Schwarzer"],
[
"occupations", [
"Student (graduated)",
"Resistance Leader",
"New Class VII Instructor"
]
],
[
"parents", {
father: "Teo",
mother: "Lucia"
}
]
];let obj = Object.fromEntries(arr);
console.log(obj);/*
{
name: "Rean Schwarzer",
occupations: [
"Student (graduated)",
"Resistance Leader",
"New Class VII Instructor"
],
parents: {
father: "Teo",
mother: "Lucia"
}
}
*/
As with the entries() method, this only converts the top-level array. The deeper arrays and objects are passed through.
What happens if our array is not formatted properly? What if the array has a primitive value or an object? What if a nested array has less than two items? What if a nested array has more than two items?
Let’s try out a few scenarios…// Non-array value
let arr = [
["first_name","Jonathan"],
"Arthur",
["last_name","Hsu"]
]let obj = Object.fromEntries(arr);
console.log(obj);
// "TypeError: Iterator value Arthur is not an entry object
When we pass in what is described as a non-entry object, then the method will return a TypeError.// Nested array item has less than two items
let arr = [
["first_name","Jonathan"],
["middle_name"],
["last_name","Hsu"],
[]
]let obj = Object.fromEntries(arr);
console.log(obj);
/*
{
first_name: "Jonathan",
last_name: "Hsu",
middle_name: undefined,
undefined: undefined
}
*/
If a nested array is empty (no items) then the resulting key-value pair is undefined: undefined, while a nested array with a single item will be treated as a key-value pair with an undefined value.// Nested array item has more than two items
let arr = [
["first_name","Jonathan"],
["middle_name","Arthur","Jones"],
["last_name","Hsu"]
]let obj = Object.fromEntries(arr);
console.log(obj);
/*
{
first_name: "Jonathan",
last_name: "Hsu",
middle_name: "Arthur"
}
*/
When a nested array has more than two items, the excess items are simply ignored.
Have you used .entries() in the past to convert objects to arrays? Do you see yourself using .fromEntries() to convert in the other direction? Share your comments and questions below!