Skip to content

Convert JSON to array JavaScript | Example code

If your JSON data is simple then you can use a loop and push() method to convert JSON to an array in JavaScript.

Example convert JSON to array JavaScript

Simple example code converts JSON object string to a JavaScript array.

<!DOCTYPE html>
<html>
<body>

  <script>
    var json_data = {"BMW":1,"FORD":7};
    var result = [];

    for(var i in json_data)
      result.push([i, json_data [i]]);


    console.log(json_data);
    console.log(result);

  </script>

</body>
</html>

Output:

Convert JSON to array JavaScript

For example with complex data

Then you need to take the values of an object Object.values(element) and make another loop over it and push it in slug

<script>
    const array = [{
      id: "4",
      club: "driver",
      afstand: "230",
      shot: "straight",
      uitvoering: "perfect"
    }, {
      id: "9",
      club: "ijzer7",
      afstand: "140",
      shot: "straight",
      uitvoering: "perfect"
    }];

    const slug = [];

    for (let i= 0; i < array.length; i += 1) {
      const element = array[i];
      Object.values(element).forEach((r) => { slug.push(r) });
    }

    console.log(array);

    console.log(slug);

</script>

If you want your outcome like this:

[
  [
    "4",
    "driver",
    "230",
    "straight",
    "perfect"
  ],
  [
    "9",
    "ijzer7",
    "140",
    "straight",
    "perfect"
  ]
]

Then you just need to add map() method only

const array1 = [{
    id: "4",
    club: "driver",
    afstand: "230",
    shot: "straight",
    uitvoering: "perfect"
}, {
    id: "9",
    club: "ijzer7",
    afstand: "140",
    shot: "straight",
    uitvoering: "perfect"
}];

const slug = array1.map((m) => { return Object.values(m); });
console.log(slug);

In both cases Object.values() is used for such operations

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS JSON to Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “Convert JSON to array JavaScript | Example code”

  1. In the year 2022, I am still very happy with the results I am getting while still using PHP, Javascript, AJAX, and JSON.

    All of the software I engineer/develop uses these technologies and with that said, I enjoyed finding the convert-json-to-array-javascript example while exploring my Linkedin profile:
    https://www.linkedin.com/in/ewittlinger/

    I have no reason to stop using PHP and to move onto another programming language like C#.
    The majority of all my programming is with Javascript and AJAX (very happy) and easy to reverse engineer.

    Ed Wittlinger

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading