Home > Net >  Javascript print array of objects
Javascript print array of objects

Time:10-10

I want to print elements of the following array of objects

  const questions = [{
    'Q1':[0, 1, 2 , 3]
  },{
    'Q2': ['true','false']
  },{
    'Q3': ['none']
  }];

I want it to print 'Q1' then its elements then 'Q2' and so on
I need them to be separated but in the same order

Q1 => 0 => 1 => 2 => 3
Q2 => true => false
Q3 => none

What is the best way to achieve this?

CodePudding user response:

Loop over your array of objects.

Then use a nested loop to loop over the questions and answers. Join the answers with =>, and combine that with the question, and print it.

const questions = [{
  'Q1': [0, 1, 2, 3]
}, {
  'Q2': ['true', 'false']
}, {
  'Q3': ['none']
}];

questions.forEach(q =>
  Object.entries(q).forEach(([question, answers]) =>
    console.log(`${question} => ${answers.join(' => ')}`)));

  • Related