jsonjavascriptarrays

How to Convert JSON to an Array in JavaScript

·7 min read·JSON Concepts

Parsing a JSON Array

If your JSON is already an array, JSON.parse() returns a real JavaScript array you can map, filter, and loop over:

javascript
const json = '[{"id":1,"name":"Ada"},{"id":2,"name":"Linus"}]';
const users = JSON.parse(json);

users.length;              // 2
users.map((u) => u.name);  // ["Ada", "Linus"]

Converting a JSON Object to an Array

Often the JSON is an object, and you want its contents as an array. JavaScript gives you three built-in methods:

MethodReturns
Object.keys(obj)array of the keys
Object.values(obj)array of the values
Object.entries(obj)array of [key, value] pairs
javascript
const data = JSON.parse('{"a":1,"b":2,"c":3}');

Object.keys(data);    // ["a", "b", "c"]
Object.values(data);  // [1, 2, 3]
Object.entries(data); // [["a",1],["b",2],["c",3]]

Object.entries() is especially useful for looping over an object as key/value pairs:

javascript
for (const [key, value] of Object.entries(data)) {
  console.log(`${key} = ${value}`);
}

Extracting an Array of Field Values

To pull a single field out of an array of objects, use .map():

javascript
const orders = JSON.parse(rawJson); // array of order objects
const ids = orders.map((o) => o.id);        // [101, 102, 103]
const totals = orders.map((o) => o.total);  // [49.9, 12.0, 8.5]

Converting a Nested Object to a Flat Array

For deeply nested JSON, flatten it first so every value is easy to reach. The JSON Flatten tool turns nested keys into dot-notation, or do it in code:

javascript
const nested = { user: { name: "Ada", address: { city: "London" } } };

const flat = Object.entries(nested).flatMap(([k, v]) =>
  typeof v === "object" && v !== null
    ? Object.entries(v).map(([k2, v2]) => [`${k}.${k2}`, v2])
    : [[k, v]]
);

From an Array of Objects to CSV

A JSON array of objects maps naturally to rows and columns. Instead of writing CSV logic by hand, paste your array into the JSON to CSV converter for a spreadsheet-ready file, or query specific values with the JSONPath Tester.

Frequently Asked Questions

How do I convert a JSON string to an array? Call JSON.parse(jsonString). If the JSON is an array, you get an array back; if it is an object, use Object.values() or Object.entries().

How do I turn an object into an array of values? Use Object.values(obj). For key/value pairs, use Object.entries(obj).

How do I get an array of one field from an array of objects? Use .map(), e.g. users.map((u) => u.email).

To inspect large arrays visually, try the JSON Explorer, and see how to parse JSON in JavaScript for the fundamentals.

Try JSONKit — JSON Developer Tools

Format, validate, convert and diff JSON. Instant, accurate and 100% private.