Open In App

How to Get a Value from a JSON Array in JavaScript ?

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are going to iterate or access the value of a JSON array in JavaScript. There are several ways and techniques to access values from the JSON Array which are explained in detail below and are further divided into several possible techniques.

Using the array[index] method

Accessing JSON array values using the numerical indexes. we can directly access the JSON array by accessing their indexes.

Example: Accessing values using the numerical index.

Javascript




let jsonArrayData = [
    {
        "ComapnyName": "GeeksforGeeks",
        "Location": "Noida"
    },
    {
        "Courses": "DSA self paced course"
    }
];
 
console.log(jsonArrayData[0]); // Accessing first element
console.log(jsonArrayData[1]); // Accessing second element


Output

{ ComapnyName: 'GeeksforGeeks', Location: 'Noida' }
{ Courses: 'DSA self paced course' }

Using the array[key] method

Accessing JSON array values within the JSON array elements using specific corresponding keys.

Example: Accessing value using keys of the arrays.

Javascript




let jsonArrayData = [
    {
        "ComapnyName": "GeeksforGeeks",
        "Location": "Noida"
    },
    {
        "topics":
            [
                "DSA self paced course",
                "Machine learning",
                "Web development",
                "Block Chain",
                "Artificial Intelligence"
            ]
    }
];
 
console.log(jsonArrayData[0]["ComapnyName"]);
console.log(jsonArrayData[1]["topics"]);


Output

GeeksforGeeks
[
  'DSA self paced course',
  'Machine learning',
  'Web development',
  'Block Chain',
  'Artificial Intelligence'
]

Using the array.slice method

Extracting JSON arrays portion of values using slice method. slice() method returns a new array containing a portion of the array on which it is implemented. The original remains unchanged.

Example: Using the slice method to access values.

Javascript




let fruitsJsonArray = [
    "Kiwi",
    "Apple",
    "Mango",
    "Guava",
    "Dates"
];
 
let slicedJsonArray = fruitsJsonArray.slice(1, 5);
console.log(slicedJsonArray);


Output

[ 'Apple', 'Mango', 'Guava', 'Dates' ]

Using for…of the loop

Accessing values from the JSON array by Iterating through each element of the JSON array. for…of statement iterates over the values of an iterable object (like Array, Map, Set, arguments object, …,etc), executing statements for each value of the object.

Syntax:

for ( variable of iterableObjectName) {
// code block to be executed
}

Example: Using for…of loop to access value.

Javascript




let jsonArray = [
    {
        "ComapnyName": "GeeksforGeeks",
        "Location": "Noida"
    },
    {
        "Courses": [
            "DSA self paced course",
            "DevOps Boot camp",
            "GATE prepration course"
        ],
        "Topics": [
            "Web Devlopment",
            "Machine Learning",
            "Artifical Intelligence"
        ]
    }
];
 
for (let element of jsonArray) {
    console.log(element);
}


Output

{ ComapnyName: 'GeeksforGeeks', Location: 'Noida' }
{
  Courses: [
    'DSA self paced course',
    'DevOps Boot camp',
    'GATE prepration course'
  ],
  Topics: [ 'Web Devlopment', 'Machine Learnin...

Using forEach()

Extracting values from the JSON arrays by executing a function for each element of the array. forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array. 

Example: Using for Each() method to access values.

Javascript




let jsonArrayData = [
  {
    "ComapnyName": "GeeksforGeeks",
    "Location": "Noida"
  },
  {
    "Courses": [
    "DSA self paced course",
    "DevOps Boot camp",
    "GATE prepration course"
    ],
    "Topics":[
    "Web Devlopment",
    "Machine Learning",
    "Artifical Intelligence"
    ]  
  }
];
 
jsonArrayData.forEach(function(element){
  console.log(element);
});


Output

{ ComapnyName: 'GeeksforGeeks', Location: 'Noida' }
{
  Courses: [
    'DSA self paced course',
    'DevOps Boot camp',
    'GATE prepration course'
  ],
  Topics: [ 'Web Devlopment', 'Machine Learnin...

Using the map() method

Accessing values from the JSON array by creating a new modified array from the existing JSON array values. map() method creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method.

Example: Using map() method to access value.

Javascript




let jsonArray = [
    {
        "ComapnyName": "GeeksforGeeks",
        "Location": "Noida"
    },
    {
        "Courses": [
            "DSA self paced course",
            "DevOps Boot camp",
            "GATE prepration course"
        ],
        "Topics": [
            "Web Devlopment",
            "Machine Learning",
            "Artifical Intelligence",
            "Data Science"
        ]
    }
];
let modifiedArray = jsonArray.map((item) => {
    return item.ComapnyName ?
        item.ComapnyName.toUpperCase() :
        item.Courses.join(", ");
});
console.log(modifiedArray);


Output

[
  'GEEKSFORGEEKS',
  'DSA self paced course, DevOps Boot camp, GATE prepration course'
]

Using filter() method

Extracting the values from the JSON array by creating a new array with the filtered elements from the original existing array. filter() Method is used to create a new array from a given array consisting of only those elements from the given array that satisfy a condition set by the argument method. 

Example: Using filter() method to access values.

Javascript




let jsonArrayData = [
    {
        "Name": "GeeksforGeeks",
        "Location": "Noida"
    },
    {
        "Courses": [
            "DSA self paced course",
            "DevOps Bootcamp",
            "GATE prepration course"
        ],
        "Topics": [
            "Web development",
            "Artifical Intelligence",
            "Machine Learning",
            "Data Science",
            "Algorithms"
        ]
    },
];
 
let filteredArrayValues = jsonArrayData
    .filter(item => item.Name === "GeeksforGeeks")
console.log(filteredArrayValues);


Output

[ { Name: 'GeeksforGeeks', Location: 'Noida' } ]

Using the find() method

Accessing the JSON array values with a first matching condition using the find() method.

Example: Using the find() method to access value from the array.

Javascript




let jsonArray = [
    {
        "Name": "GeeksforGeeks",
        "Location": "Noida"
    },
    {
        "Courses": [
            "DSA self paced course",
            "DevOps Bootcamp",
            "GATE prepration course"
        ],
        "Topics": [
            "Web development",
            "Artificial Intelligence",
            "Machine Learning",
            "Data Science",
            "Algorithms"]
    },
];
 
let filteredJsonArrayValues = jsonArray
    .find(item => item.Name === "GeeksforGeeks");
console.log(filteredJsonArrayValues);


Output

{ Name: 'GeeksforGeeks', Location: 'Noida' }

Using findIndex() method

findIndex() method is used to return the first index of the element in a given array that satisfies the provided testing function (passed in by the user while calling). Otherwise, if no data is found then the value of -1 is returned.

Example: Using the findIndex() method to access values.

Javascript




let jsonArrayValues = [
    {
        "Name": "GeeksforGeeks",
        "Location": "Noida"
    },
    {
        "Courses": [
            "DSA self-paced course",
            "DevOps Bootcamp",
            "GATE preparation course"
        ],
        "Topics": [
            "Web development",
            "Artificial Intelligence",
            "Machine Learning",
            "Data Science",
            "Algorithms"
        ]
    }
];
 
let index = jsonArrayValues
    .findIndex(item => item.Name === "GeeksforGeeks");
 
// Check if the item is found before trying to log it
if (index !== -1) {
    console.log(jsonArrayValues[index]);
} else {
    console.log("Item not found");
}


Output

{ Name: 'GeeksforGeeks', Location: 'Noida' }

Using some() method

Accessing those values from the JSON array where some of the conditions are met in the array. Some() method checks whether at least one of the elements of the array satisfies the condition checked by the argument method. 

Example: Using some() method to access values from the array.

Javascript




let jsonArray = [
    {
        "Name": "GeeksforGeeks",
        "Location": "Noida"
    },
    {
        "Courses": ["DSA self-paced course",
            "DevOps Bootcamp",
            "GATE preparation course"],
 
        "Topics": ["Web development",
            "Artificial Intelligence",
            "Machine Learning",
            "Data Science",
            "Algorithms"]
    }
];
 
let Item = null;
 
jsonArray.some(item => {
    if (item.Name === "GeeksforGeeks") {
        Item = item;
        // This will exit the loop once the item is found
        return true;
    }
});
 
if (Item !== null) {
    console.log(Item);
} else {
    console.log("Item not found");
}


Output

{ Name: 'GeeksforGeeks', Location: 'Noida' }

Using recursive traversal of JSON array

Accessing the values from the JSON array by creating the custom function for seamless navigation.

Example: Using recursive traversal for accessing values.

Javascript




function JsonArrayTraversal(object) {
    for (let key in object) {
        if (typeof object[key] === 'object') {
            JsonArrayTraversal(object[key]);
        } else {
            console.log(object[key]);
        }
    }
}
 
let jsonArray = {
    "name": "GeeksforGeeks",
    "location": "Noida",
    "Courses": [
        "DSA self paced course",
        "DevOps Bootcamp",
        "GATE preparation course"
    ]
};
 
JsonArrayTraversal(jsonArray);


Output

GeeksforGeeks
Noida
DSA self paced course
DevOps Bootcamp
GATE preparation course

Using the custom reduce method

Accessing values from the JSON array by using the custom reduced method. reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator. 

Example: Using the custom reduce method for accessing values from the JSON arrays.

Javascript




let jsonArrayData = [
    {
        "name": "GeeksforGeeks",
        "location": "Noida"
    },
    {
        "course": [
            "DSA self paced course",
            "DevOps Bootcamp",
            "GATE preparation course"
        ]
    }
];
 
function customReduceMethod(arr, func, initialValue) {
    let accumulator = initialValue;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].name) {
            accumulator = func(accumulator, arr[i].name);
        }
    }
    return accumulator;
}
 
let data = customReduceMethod(jsonArrayData, (acc, val) => {
    return acc + val;
}, '');
 
console.log(data);


Output

GeeksforGeeks

Using custom classes

Extracting values from the JSON array by creating custom classes.

Example: Using custom classes for accessing values.

Javascript




class value {
    constructor(jsonArray) {
        this.jsonArray = jsonArray;
    }
 
    getValue(index) {
        return this.jsonArray[index];
    }
}
 
// Example usage
const jsonArray = [{
    "name": "GeeksforGeeks",
    "Location": "Noida"
},
{
    "courses":
        [
            "DSA self paced",
            "DevOps Boot camp"
        ]
}
];
const myData = new value(jsonArray);
console.log(myData.getValue(1));


Output

{ courses: [ 'DSA self paced', 'DevOps Boot camp' ] }


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads