JSON - Access data structure

By xngo on September 10, 2019

When working with JSON data, you often get an array of objects. For the current example below, the object represents a person with name and age properties. Most of the time, what you really need in the end is individual array containing only each property. There are multiple ways to achieve this. However, using .map() function is a neat way to do this. It returns a new array with the results of calling a function for every array element. Here is an example showing how to get an array of values for each property.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON - Examples</title>
    <script>
        // Declare JSON structure.
        var jsonfile = {
                        "persons": [
                                { "name": "Joe", "age": 12 },
                                { "name": "Tom", "age": 14}
                            ]
                        }
 
        // Extract data using map().
        var names = jsonfile.persons.map(function(e) { return e.name; });
        var ages = jsonfile.persons.map(function(e) { return e.age; });
 
        // Access and display data.
        for( $i=0; $i<names.length; $i++ ) {
            console.log(names[$i] + " is " + ages[$i] + " years old.");
        }
    </script>
</head>
<body>
</body>
</html>

Output

JSON - Declare & access console results

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.