This page looks best with JavaScript enabled

Convert JSON to Array in Javascript

 ·   ·  ☕ 1 min read

Often my server DB functions return the data in JSON format with all fields and values thrown in.

1
const alphaNum = { a: 1, b: 2, c: 3, d: 4, e: 5 };

When we use charts (or even tables), this needs to be converted to an array of arrays. Most of the iterative functions work well with arrays and not objects.

We would want to convert the object into [['a', 1], ['b', 2]...].

Use Object.keys

We can convert JSON to array by using a map function on Object.keys.

1
2
3
4
const alphaNumOut = Object.keys(alphaNum).map(key => [key, alphaNum[key]]);

console.log("alphaNumOut: ", alphaNumOut);
// [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ], [ 'd', 4 ], [ 'e', 5 ] ]
Use the evil for-in

Although slower, for-in results in a readable (?) loop.

1
2
const alphaNumOut = [];
for (let element in alphaNum) alphaNumOut.push([element, alphaNum[element]]);
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things