0

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?

1
  • Use Array.join() to convert the arrays to strings separated by =>. Loop over the object properties, using that on each value.
    – Barmar
    Oct 9, 2022 at 22:50

1 Answer 1

1

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(' => ')}`)));

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.