How to use reduce method by loadash for nested/complex object

Viewed 47

I have data like this

const faq = 
{
Question1:{
   question:’Question1’,
   answer: {
       Answer1_1: {
          answer: ‘Answer1_1’
       },
       Answer1_2: {
          answer: ‘Answer1_2’
       }
    }
},
Question2:{
   question:’Question2’,
   answer: {
       Answer2_1: {
          answer: ‘Answer2_1’
       },
       Answer2_2: {
          answer: ‘Answer2_2’
       }
    }
}
}

And the expected result I want is

[
    {
    question: ’Question1’
    answer: [‘Answer1_1’, ‘Answer1_2’]
    }, 
    {
    question: ’Question2’
    answer: [‘Answer2_1’, ‘Answer2_2’]
    }
]

From what I understood I made a function like this:

const convertQuestionTypesToMap = compose(
    reduce(
        (map, {question, answer}) => ({...map, [question]: question}),
        {}
    ),
    map(([question, value]) => value),
    toEntries
);

I am not getting the expected result. Can anyone correct my function?

2 Answers

You can achieve it only using Javascript using Object.values and Array.prototype.map.

Using Array.map

const data = { Question1: { question: "Question1", answer: { Answer1: { answer: "Answer1_1", }, Answer2: { answer: "Answer1_2", }, }, }, Question2: { question: "Question2", answer: { Answer1: { answer: "Answer2_1", }, Answer2: { answer: "Answer2_2", }, }, }, };

const output = Object.values(data).map(({ question, answer }) => {
    return {
        question,
        answer: Object.values(answer).map(({ answer }) => answer),
    };
});

console.log(output);

Using Array.reduce

const data = { Question1: { question: "Question1", answer: { Answer1: { answer: "Answer1_1", }, Answer2: { answer: "Answer1_2", }, }, }, Question2: { question: "Question2", answer: { Answer1: { answer: "Answer2_1", }, Answer2: { answer: "Answer2_2", }, }, }, };

const output = Object.values(data).reduce((prev, { question, answer }) => {
  prev.push({
    question,
    answer: Object.values(answer).reduce((prevVal, { answer }) => {
      prevVal.push(answer);
      return prevVal;
    }, []),
  });
  return prev;
}, []);

console.log(output);

You can do it using for in loop;

First for in loop for push the question in main array and second for in loop for get answer in child objects

 let newArr = [];
    let arr = [];
    for (key in Data) {
      //get the question from each object
      let question = Data[key].question; 
      arr = []; 
      for (child in Data[key].answer) { 
        //get answer from child object
        arr.push(Data[key].answer[child].answer); 
      }
      newArr.push({
        question: question,
        answer: arr
      });
    }
    console.log(JSON.stringify(newArr), 'newArr');
Related