0

I want to loop an array inside object. Here's my code. What I want to achieve is, for example, I click the How to make pancake? button, and it redirects me to another page where it shows an (bootstrap) accordion full of questions from this js file

export const questionList = [
  {
    slug: "how-to-make-pancake",
    title: "How to make pancake?",
    questions: [
      {
        id: 1,
        question: "First question?",
        answer: "First Answer"
      },
      {
        id: 2,
        question: "Second question?",
        answer: "blablablabla"
      }
    ]
  },
  {
    slug: "how-to-make-pancake2",
    title: "How to make pancake2?",
    questions: [
      {
        id: 1,
        question: "First question?",
        answer: "First Answer"
      },
      {
        id: 2,
        question: "Second question?",
        answer: "blablablabla"
      }
    ]
  },
  {
    slug: "how-to-make-pancake3",
    title: "How to make pancake3?",
    questions: [
      {
        id: 1,
        question: "First question?",
        answer: "First Answer"
      },
      {
        id: 2,
        question: "Second question?",
        answer: "blablablabla"
      }
    ]
  }
];

in the accordion.vue, I think this line of code doesn't work

data() {
    return {
      questionslist: questionList.questions,
    };
  }

My question is, how to access the questions array in every object in the questionList? I'm sorry if it's kinda confusing and my language is not good. Thank you so much.

1
  • Since 'questionList' is an array, you cannot access 'questions' as 'questionList.questions'. You would need 'questionList[arrayIndex].questions'. One of the existing answers may do what you want, but just wanted to clarify. Commented Feb 18, 2021 at 15:13

2 Answers 2

1

You can use flat():

data() {
  return {
    questionsList: questionList.map(q => q.questions).flat();
  };
}
Sign up to request clarification or add additional context in comments.

1 Comment

it gives me an error You may need an additional loader to handle the result of these loaders. | data () { | return { > questionsList: questionList.map(q => q.questions).flat(); | } | } what kind of loader do i need?
0

So you want to flatten all of the questions arrays into a single array? You can do it like this:

data() {
  return {
    questionsList: questionList.reduce((res, obj) => {
      return [...res, ...obj.questions];
    }, [])
  };
}

Comments

Your Answer

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