To access JSON key and value in JavaScript, you can use the dot notation or bracket notation. For example, to access the value of the "name" property of the "departureAirport" object in the "outbound" object, you can use either:
fare.outbound.departureAirport.name
or
fare["outbound"]["departureAirport"]["name"]
To iterate over an array of objects, you can use the forEach()
method. The forEach()
method takes a callback function as an argument. The callback function is executed for each element in the array. For example, the following code iterates over the fares
array and logs the values of the "name" property of the "departureAirport" and "arrivalAirport" objects in the "outbound" object, as well as the "departureDate" and "price.value" properties of the "outbound" object:
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);
})
To select certain values from an array of objects, you can use the filter()
method. The filter()
method takes a callback function as an argument. The callback function is executed for each element in the array. The callback function returns a boolean value. If the callback function returns true
, the element is included in the filtered array. For example, the following code selects the fares that have a "price.value" greater than 100:
const filteredFares = fares.filter((fare) => {
return fare.outbound.price.value > 100;
});
You can also use the map()
method to transform each element in an array of objects. The map()
method takes a callback function as an argument. The callback function is executed for each element in the array. The callback function returns a new value. The new values are stored in a new array. For example, the following code creates a new array of objects that contain only the "name" property of the "departureAirport" and "arrivalAirport" objects in the "outbound" object, as well as the "departureDate" and "price.value" properties of the "outbound" object:
const transformedFares = fares.map((fare) => {
return {
departureAirport: fare.outbound.departureAirport.name,
arrivalAirport: fare.outbound.arrivalAirport.name,
departureDate: fare.outbound.departureDate,
price: fare.outbound.price.value,
};
});