DevOverflow
DevOverflow

Reputation: 1762

Complex transformation of an array of objects into another array

I have an array of objects, each object is a field with a name and an array of questions, how can I bring this structure into an array of objects, where the object will be questions, and if such a question has already been asked, it should not be repeated.

  let object = [
      {name: 'first', questions: [
        {name: 'question1', answer: {name: 'answer1'}},
       {name: 'question2', answer: {name: 'answer2'}}
      ]},
       {name: 'second', questions: [
        {name: 'question3', answer: {name: 'answer3'}},
        {name: 'question1', answer: {name: 'answer1'}}
      ]}
    ]

  //exprected => 

let result = [
  {qeustion: 'qeustion1', answer: {name: 'answer1'}},
  {qeustion: 'qeustion2', answer: {name: 'answer2'}},
  {name: 'question3', answer: {name: 'answer3'}}
]

I am stuck with the following transformation, I tried to do it with reduce but nothing worked

Upvotes: 0

Views: 39

Answers (1)

ThS
ThS

Reputation: 4783

To start, using reduce is a good approach but reduce only won't give you the desired end result.

You need also to loop through the questions array and check if the current question has been already added to the resulting array (you didn't mention how to check if a question is duplicate so am assuming that the question's name should be checked against). If the question is not a duplicate, then push it to the resulting array.

Here's a demo:

let object = [
  {
    name: "first",
    questions: [
      { name: "question1", answer: { name: "answer1" } },
      { name: "question2", answer: { name: "answer2" } }
    ]
  },
  {
    name: "second",
    questions: [
      { name: "question3", answer: { name: "answer3" } },
      { name: "question1", answer: { name: "answer1" } }
    ]
  }
];

let transform = arr =>
  arr.reduce((a, c) => {
    c.questions.forEach(
      q => 0 > a.findIndex(el => el.question == q.name)
           && a.push({ question: q.name, answer: q.answer })
    );
    return a;
  }, []);

console.log(transform(object));

Hope that helps, if you still need any further assistance feel free to ask.

Upvotes: 1

Related Questions