0

I have below JSON object from which I want to fetch only certain values on my dev console log using javascript. I tried but below code but I don't know how to loop through array of array. Can anyone please suggest how can i achieve this.

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 trying to write JavaScript function that outputs the total number of subjects, each subject with marks, and average marks in the browser dev tools console in format given below.

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

The code should work for ANY JSON object with the same structure so don't want to use hard coded keys (eg. maths,physics)

Ankit Fulzele
  • 327
  • 5
  • 15
  • You can look into using `map`-functions or `lodash`, if you want to keep the code short and clean. – molerat Jun 14 '18 at 19:49

3 Answers3

1

It would be just a question of checking what you are iterating in your class. In case the key is a string, you can simply print it, in case it is not, you can iterate it keys, and print that one

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') );
Icepickle
  • 12,689
  • 3
  • 34
  • 48
  • Thank you so much it worked for me with expected output. I am new to this and I am trying to learn JavaScript...I would really appreciate if you could suggest good tutorials on web – Ankit Fulzele Jun 14 '18 at 19:58
  • @AnkitFulzele You are welcome, I don't really know where to start at this time, depends on what you want to do with your learnings. [MDN](https://developer.mozilla.org/en-US/docs/Learn) has a learning guide, and as they offer quite good documentation, I would start watching there... – Icepickle Jun 14 '18 at 20:26
0

This can be done using simple for in , Object.keys().

Try the following:

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]);
   }
}
amrender singh
  • 7,949
  • 3
  • 22
  • 28
  • Thank you so much this also worked for me...but somewhat difference in output which I was looking. Thank you so much for you response which gives me opportunity to learn new thing. :) – Ankit Fulzele Jun 14 '18 at 20:01
0

Subjects and Average are always at the same position, so you hardcode it. Then you have to go on the array to determine the other fields:

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']);
Johan B
  • 394
  • 1
  • 10