What is the best way to retrieve values from a JSON object without knowing the specific key?

Given the JSON object below, I am looking to extract specific values using JavaScript in my browser's dev console. However, I am not sure how to loop through an array of arrays. Can anyone provide guidance on achieving this task?

var infoJSON;
for(key in myClass) {
  infoJSON = myClass[key];
  console.log(infoJSON);
}




var myClass= {
   "Subjects":"3",
   "Subject":{
      "maths":{
         "subject_id":"1",
         "subject_level":"easy",
         "marks":"90"
      },
      "english":{
         "subject_id":"2",
         "subject_level":"medium",
         "marks":"80"
      },
      "physics":{
         "subject_id":"3",
         "subject_level":"tough",
         "marks":"70"
      }
   },
   "Average": "80"
};

I am working on a JavaScript function that will display the total number of subjects, each subject with its marks, and the average marks in the browser console as shown below.

Subjects: 3
- maths (90)
- english (80)
- physics (70)
Average: 80

The goal is for the code to be dynamic and work with any JSON object following the same structure without hardcoding keys such as maths or physics.

Answer №1

To determine what you are iterating in your class, you should check if the key is a string. If it is a string, you can print it directly. If it is not a string, iterate through its keys and then print them.

var myClass= {"Subjects":"3","Subject":{"maths":{"subject_id":"1","subject_level":"easy","marks":"90"},"english":{"subject_id":"2","subject_level":"medium","marks":"80"},"physics":{"subject_id":"3","subject_level":"tough","marks":"70"}},"Average":"80"};

for (let key in myClass) {
  let value = myClass[key];
  if (typeof value === 'string') {
    console.log( `${key}: ${value}` );
    continue;
  }
  console.log( Object.keys( value ).map( k => `- ${k} (${value[k].marks})` ).join('\n') );
}

// if you want it in one log output
console.log( Object.keys( myClass ).reduce( (result, key) => {
  if (typeof myClass[key] === 'object') {
    let value = myClass[key];
    return result.concat( Object.keys( value ).map( k => `- ${k} (${value[k].marks})` ) );
  }
  result.push( `${key}: ${myClass[key]}` );
  return result;
}, [] ).join('\n') );

Answer №2

To achieve this, you can utilize basic for in, Object.keys().

Give this a try:

var myClass= {"Subjects":"3","Subject":{"maths":{"subject_id":"1","subject_level":"easy","marks":"90"},"english":{"subject_id":"2","subject_level":"medium","marks":"80"},"physics":{"subject_id":"3","subject_level":"tough","marks":"70"}},"Average":"80"};

for(key in myClass){
  if(myClass[key].constructor.toString().indexOf("Object") > 0){
      Object.keys(myClass[key]).forEach((k)=> {
        console.log(k +" - "+ myClass[key][k].marks);
      });
   } else{
    console.log(key +" - " +myClass[key]);
   }
}

Answer №3

In this code snippet, the relationship between Subjects and Average is fixed which allows for hardcoded values. However, the other fields within the array require iteration to access:

var myClass= {
   "Subjects":"3",
   "Subject":{
      "maths":{
         "subject_id":"1",
         "subject_level":"easy",
         "marks":"90"
      },
      "english":{
         "subject_id":"2",
         "subject_level":"medium",
         "marks":"80"
      },
      "physics":{
         "subject_id":"3",
         "subject_level":"tough",
         "marks":"70"
      }
   },
   "Average": "80"
};
var infoJSON;
console.log('Subjects: ' + myClass['Subjects']);
for(key in myClass['Subject']) {
  console.log('- ' + key + ' (' + myClass['Subject'][key]['marks'] + ')');
}
console.log('Average: ' + myClass['Average']);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error occurred while making a request in React using Axios: TypeError - Unable to retrieve the 'token' property as it is undefined

After successfully receiving a token from logging in with React Redux, I attempted to authorize it using the token. However, an error occurred stating Axios request failed: TypeError: Cannot read property 'token' of undefined. The token is stored ...

Is there a way to develop a login form that retrieves information from a Google Sheet database?

Please help me with a solution. I have developed a registration form which effectively saves users' information in a Google Sheet. However, now I am yearning to create a login form that verifies the stored data and redirects the user to a different pa ...

Leveraging oEmbed - JSON data (within client-side JavaScript)

Is it feasible to utilize an oembed provider that solely produces json and xml outputs on the client side using javascript (through a $.ajax request to the provider)? Do we need to rely on oembed providers that enable a jsonp callback in javascript for th ...

Update the 'duplicate' buttons according to the position in the array

My app features 14 buttons, each generating a replica button with the same text when clicked. The pre-existing buttons are numbered to aid in iteration. I'm currently attempting to organize the newly created replica buttons in ascending order from lef ...

Combine JavaScript array objects based on their unique IDs

Looking to combine 2 arrays of objects based on IDs (ID and AUTOMOBIL). However, the current code only saves the last array of objects (OPREMA). Any suggestions on how to merge all of them correctly? If the ID in a1 is == 1, I want to save all OPREMA wher ...

Determining the XY position of the wheel data

In my attempt to develop a lucky draw wheel using reactjs, I needed to position all the input data at specific XY coordinates. Below is an example of the expected output XY positions that I require. var renderData = ["1", "2", "3", "4", "5", "6", "7", " ...

Retrieve and showcase PHP results utilizing the power of jQuery/AJAX

I am working with a Leaflet map and a text input field. My goal is to extract the address from the text input, process it using a PHP script, and receive the results back via jQuery. Below is the form structure: <form id="mapcheck" method="POS ...

Navigating Highcharts within jQuery

I am looking to integrate some new data into an existing Highchart on the page using the following code snippet: window['chart_' + skill_id].series[0].addPoint(data, true, false); This method works perfectly if I originally created the chart li ...

How can I efficiently delete a property from a nested array of references in MongoDB using Mongoose.js, leveraging the populate method, and also utilizing one of the subarray fields as a filter?

In my Node.js code using the Mongoose package, I have the following questions: 1) When using the populate method, how can I remove the "total" field within the foundations array from the response? This array consists of references to another collection. ...

Tips for converting PL/SQL JSON values into a string

Working on a project at work, my SQL skills are improving but I still struggle with some basic issues from time to time. Right now, I need to display 'fundingCode' as a string instead of a number. (Currently it appears as ""fundingCode" ...

Utilize the ng-click feature for swiping interactions in Ionic v1

I have a slide page on Ionic V1 that utilizes previous and next buttons. Here is an example: <button id="" class="button button-slide prev no-animation" ng-click="prev()" ng-show="activeIndex > 0" > BACK </button> While the click function ...

The integration of AngularJS with Bootstrap 3 accordion seems to encounter issues when included through ng-view

Here's the issue: When using the accordion in a view loaded with the ng-view directive, the accordion title clicks stop working correctly. Check out this demo for an example However, when the accordion is used directly on the page without ng-view, i ...

Select an option within a for loop nested in an each function

How To Fetch JSON Data and Create a Shopping Cart $.ajax({ url: "myurl", type: 'POST', dataType: "json" }).done(function(response){ $.each(response,function(k,v){ //UL this products info list ...

What is the reason for seeing identical results when logging an array to console both before and after performing an operation on it?

Let's consider this scenario: var currentHistory = ['t1', 't2', 't3', 't4', 't5']; console.log(currentHistory); Next, we decide to swap an element and display the array again: ...

Is there a way to assign a numerical value to the data attribute of the "p" tag?

As beginners in coding, we are introduced to various value types such as strings ("Hello"), booleans (true), and numbers (1). I am curious, how can I assign a number value to a <p> tag instead of a string? Is there a specific number tag that should ...

Tips for extracting a $scope object containing various objects from a web API

What is the best way to pass an object that contains multiple objects within it, each with unique key-value pairs? Here is an example of the data structure: [ Object, Object, Object, Object ] 0 : Object ProductID : "50" __proto__ : Object 1 : Object Brand ...

Utilize HighCharts to seamlessly implement multiple series with the help of AJAX requests

I am facing an issue with plotting the performance results on HighCharts using AJAX. The problem lies with the .addSeries API call not functioning correctly. I need assistance in determining if my approach is correct. $(function () { $('#chart3&a ...

Convert HTML tr elements into a PHP array

After realizing that my previous thread lacked clarity, I decided to delete it and start fresh. In my php script, I send a cURL request to a website which generates an HTML table. This table contains 7 TR elements, each containing 6 TD elements. Essentia ...

Looking for a specific item within a JSON string array using Google Apps Script

I've set up a Google Apps Script linked to a sheet and deployed as a web app to serve as a webhook for data collection. The script successfully captures the first two results (adding them to the sheet) without any issues, with time going into column 1 ...

Can we create a class to represent a JSON object?

Can a JSON be modeled with a class in TypeScript (or Angular)? For example, I am using Firebase and have a node called /books structured like this: books -- 157sq561sqs1 -- author: 'Foo' -- title: 'Hello world' (Where 1 ...