Home > Software design >  How to loop through a arrays in an object and print values of only specific keys?
How to loop through a arrays in an object and print values of only specific keys?

Time:11-08

I have an object named responses that consists of arrays as keys like this

responses = { 
  'Day': [1,2,3,4,5,6,7,8,9,10],
  'Score': [9,10,9,8,8,9,10,9,8,7],
  'Grade': ['A','O','A','B','B','A','O','A','B','C']
}

I want to loop through the object and only print the Score and Grade values, like this:

9   'A'
10  'O'
9   'A'
.    .
.    .
.    .
7   'C'

How do print this?

CodePudding user response:

You can do it by index callback of Array.prototype.map() function.

Try:

const responses = {
  Day: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  Score: [9, 10, 9, 8, 8, 9, 10, 9, 8, 7],
  Grade: ['A', 'O', 'A', 'B', 'B', 'A', 'O', 'A', 'B', 'C'],
};

responses.Day.map(
  (day, i) => console.log(responses.Score[i], responses.Grade[i]) // 9 B
);

CodePudding user response:

You can use for in loop. See here for further information.

for (const response in responses) 
{ 
    if (response === "Score")
    {
        responses[response].forEach(item => {
            console.log(item); 
        }); 
        
        // do something else 
    } 
    else if (response === "Grade") 
    {
        responses[response].forEach(item => {
            console.log(item); 
        }); 

        // do something else 
    } 
}
  • Related