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

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

Comments

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.