SkinnyBetas
SkinnyBetas

Reputation: 501

Iterating over object that contains objects to use result

I've got a React program that asks a user a bunch of different questions, once the user has finished they're taken to basically a results page. Now on that page I want to display results in a meaningful way depending on the answers given. But I am having trouble using the object that contains all the answers.

The survey questions return an object with multiple objects inside, what I'd like to do is iterate over the object and say for example if "what color is the sky" == "blue" correct_answers += 1 or something like that. But it gets a little more complex where some of the nested objects hold an array, while others might hold another object.

The returned answer object looks like this:

Object {
   "whats 2 + 2" : "4"
   "what color is the sky" : "blue"
   "which are breeds of dog" : ["golden retriever", "pug"]
   "do you like studying" : Object {row 1: "3", row 2: "5", row 3: "2"}
}

The return type of the object is dependent on what form of question it is, if the user can answer multiple things it returns an array whereas a matrix type of question where they rate certain things on a scale returns another object like "do you like studying".

Is there a way to iterate over answers like this? Or would I have to go about it in a different way. Any help would be greatly appreciated.

Upvotes: 3

Views: 85

Answers (2)

Namaskar
Namaskar

Reputation: 2109

You can use object's entries function to get key value pairs and then iterate over them. Here use array destructing to get the key and value.

Object.entries(object).forEach(([key, value]) => { /* do something */})

let answers = {
  "whats 2 + 2": "4",
  "what color is the sky": "blue",
  "which are breeds of dog": ["golden retriever", "pug"],
  "do you like studying": {
    science: "3",
    math: "5",
    art: "2"
  }
}

const dogs = ["golden retriever", "poodle", "pug"];

Object.entries(answers).forEach(([key, value]) => {
  switch (value.constructor.name) {
    case 'Array':
      console.log(`${key}? ${value.map(dog => `${dog}${dogs.includes(dog) ? '✔️' : '❌'}`)}`);
      break;
    case 'Object':
      Object.entries(value).forEach(([key, value]) => {
        console.log(`On a scale of 1-5, how much do you like studying ${key}? ${value} ${value >= 3 ? '✔️' : '❌'}`);
      });
      break;
    default:
      console.log(`${key}? ${value === "4" || value === 'blue' ? '✔️' : '❌' }`);
      break;
  }
});

Upvotes: 1

ROOT
ROOT

Reputation: 11622

You can use Object.keys() and .forEach() to iterate over the main data object then, you check for the object item type using Array.isArray() and .typeof() You can iterate over your structure like this :

let answers =  {
   "whats 2 + 2" : "4",
   "what color is the sky" : "blue",
   "which are breeds of dog" : ["golden retriever", "pug"],
   "do you like studying" : {row1: "3", row2: "5", row3: "2"}
}

Object.keys(answers).forEach((el) => {
  if(Array.isArray(answers[el])) {
    answers[el].forEach((answer) => {
      console.log('Inside Array: ', answer);
    });
    
  } else if(typeof answers[el] === 'object') {
     Object.keys(answers[el]).forEach((key) => {
       console.log('Inside nested Object: ', key, answers[el][key]);
     });
  }
  else {
    console.log('Object entry: ' + answers[el]);
  }
});

Upvotes: 2

Related Questions