How to Get a Value from a JSON Array in JavaScript?
To retrieve a value from a JSON array in JavaScript, we can use various methods such as accessing the array by index or using built-in methods like find(), map(), etc.
1. Accessing Values by Index
In a JSON array, values are stored in an ordered list, which means you can directly access a value by its index.
Syntax:
arr[index];
- arr: The JSON array.
- index: The position of the item you want to access.
let a = [
{ "name": "Sourav", "age": 23 },
{ "name": "Ajay", "age": 25 }
];
let val = a[0].name;
console.log(val);
Output
Sourav
In this example:
- arr[0] accesses the first object in the array.
- .name accesses the name property of that object.
- The output will be "Sourav", the value of the name property in the first object.
2. Using the find() Method
The find() method allows you to find an object within a JSON array based on a condition.
Syntax:
arr.find(callback);
- arr: The JSON array.
- callback: A function that tests each element of the array. The find() method returns the first element that satisfies the condition in the callback.
let a = [
{ "name": "Sourav", "age": 23 },
{ "name": "Ajay", "age": 25 }
];
let person = a.find(item => item.name === "Ajay");
console.log(person.age);
Output
25
3. Using map() Method
The map() method is useful when you need to retrieve values from a property of each object in the array.
Syntax:
arr.map(callback);
let a = [
{ "name": "Sourav", "age": 23 },
{ "name": "Ajay", "age": 25 }
];
let names = a.map(item => item.name);
console.log(names);
Output
[ 'Sourav', 'Ajay' ]
In this example
- The map() method iterates through each object in the array.
- For each object, it returns the name property, which results in a new array ["Sourav", "John"].
4. Using forEach() Method
The forEach() method is used to iterate through each element of the array and access the values.
Syntax:
arr.forEach(callback);
let a = [
{ "name": "Sourav", "age": 23 },
{ "name": "Ajay", "age": 25 }
];
a.forEach(item => {
if (item.name === "Sourav") {
console.log(item.age);
}
});
Output
23
In this example:
- The forEach() method iterates through each object in the array.
- For each object, it checks if the name property is "Sourav". If true, it logs the age property.
5. Using filter() Method
If you need to retrieve multiple values based on a condition, you can use the filter() method.
Syntax:
arr.filter(callback);
let a = [
{ "name": "Sourav", "age": 23 },
{ "name": "Ajay", "age": 25 },
{ "name": "Sourav", "age": 30 }
];
let res = a.filter(item => item.name === "Sourav");
console.log(res);
Output
[ { name: 'Sourav', age: 23 }, { name: 'Sourav', age: 30 } ]
In this example
- The filter() method returns all objects in the array where the name property is "Sourav".
- In this case, two objects match, and the result is an array containing both objects.