Convert Object to Array in JavaScript

Convert Object to Array in JavaScript

  1. Use Object.keys() and map() to Convert an Object to an Array in JavaScript
  2. Use Object.entries() to Convert an Object to an Array in JavaScript

Objects are non-primitive data types forming the building blocks of modern JavaScript. Unlike primitive data types that are singular, objects can constitute several primitive data types in a complex fashion.

An array is a single variable used to store a list of elements. This tutorial explains how to convert an object to an array of key-value pairs in JavaScript.

Use Object.keys() and map() to Convert an Object to an Array in JavaScript

The Object.keys() method helps retrieve all the enumerable properties in an object into an array of strings. It takes the object obj as an argument, and we can add a callback function to get the desired result.

To convert an object to an array we first call the Object.keys() method on the object, and then we call the map() function on its output to map the key and value of the object in the corresponding array. It will contain the properties in the same order as the object.

var obj = { "2": 3, "1": 37, "23": 40, "41": 220, "115": 230 };
var arr = Object.keys(obj).map(function (key) {return [Number(key), obj[key]];});
console.log(arr);

Output:

[[1, 37], [2, 3], [23, 40], [41, 220], [115, 230]]

Use Object.entries() to Convert an Object to an Array in JavaScript

The Object.entries() method works similar to the Object.keys() method, and you can also use it to convert an object to an array. But it returned only the keys, and we had to use the map() function to recreate the enumerable object properties in the array.

Object.entries() simplifies the task by directly returning the answer in an array. Like Object.keys(), the properties are returned in the same order as the object.

var obj = { "2": 3, "1": 37, "23": 40, "41": 220, "115": 230 };
var arr = Object.entries(obj);
console.log(arr);

Output:

[
  [ '1', 37 ],
  [ '2', 3 ],
  [ '23', 40 ],
  [ '41', 220 ],
  [ '115', 230 ]
]

Related Article - JavaScript Object

  • Search Objects From an Array in JavaScript
  • Find Object in Array by Property Value in JavaScript
  • Print Objects in JavaScript
  • JavaScript Destroy Object
  • JavaScript Destroy Object
  • Nested Objects in JavaScript
  • Related Article - JavaScript Array

  • Check if Array Contains Value in JavaScript
  • Create Array of Specific Length in JavaScript
  • Convert Array to String in JavaScript
  • Remove First Element From an Array in JavaScript
  • Search Objects From an Array in JavaScript
  • Convert Arguments to an Array in JavaScript