Notification texts go here Contact Us Buy Now!

How to get JSON key and value and select certain values in javascript?

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 using data.name.
  • Using the bracket notation, you can access a key by specifying it within square brackets. For example, to access the "name" key of the data object, you can use data["name"].
To select certain values from a JSON object in JavaScript:
  • 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.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.