Getting JSON Key and Value, then Selecting Certain Values in JavaScript
In JavaScript, JSON (JavaScript Object Notation) is frequently utilized to exchange and process data. JSON is similar to JavaScript objects, and just like them, it can be traversed and manipulated to extract specific data structures.
To get JSON key and value in JavaScript:- You can access a JSON object's key using the dot notation (.) or the bracket notation ([]).
- Using the dot notation, you can access a key directly. For example, if you have a JSON object called
data
with a key"name"
, you can access its value usingdata.name
. - Using the bracket notation, you can access a key by specifying it within square brackets. For example, to access the
"name"
key of thedata
object, you can usedata["name"]
.
- You can use the
forEach()
method to iterate over an array of JSON objects and extract specific values from each object. - For example, let's say you have an array of JSON objects representing airline fares called
fares
. Each fare object has properties such as"outbound"
,"arrivalAirport"
,"departureDate"
, and"price"
. - To extract the
"departureAirport"
,"arrivalAirport"
,"departureDate"
, and"price"
values for each fare, you can use the following code:
fares.forEach((fare) => {
console.log(fare.outbound.departureAirport.name);
console.log(fare.outbound.arrivalAirport.name);
console.log(fare.outbound.departureDate);
console.log(fare.outbound.price.value);
});
Alternatively, you can use the map()
method to create a new array containing the selected values:
const selectedValues = fares.map((fare) => ({
departureAirport: fare.outbound.departureAirport.name,
arrivalAirport: fare.outbound.arrivalAirport.name,
departureDate: fare.outbound.departureDate,
price: fare.outbound.price.value,
}));
In this example, the map()
method iterates over the fares
array, applies the provided function to each fare object, and returns a new array containing the specified values. You can then access the selected values from the selectedValues
array.