Convert JSON to array JavaScript | Example code

  • by

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

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

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.