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)

1
  • You can look into using map-functions or lodash, if you want to keep the code short and clean. Commented Jun 14, 2018 at 19:49

3 Answers 3

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') );

Sign up to request clarification or add additional context in comments.

2 Comments

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
@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 has a learning guide, and as they offer quite good documentation, I would start watching there...
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]);
   }
}

1 Comment

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. :)
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']);

1 Comment

Thank you so much @Johan Bertrand..it is again simplest way to achieve desired output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.