3

我有这样的数据

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’
       }
    }
}
}

我想要的预期结果是

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

据我了解,我做了一个这样的函数:

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

我没有得到预期的结果。谁能纠正我的功能?

4

2 回答 2

2

您只能使用 JavaScript 使用Object.valuesArray.prototype.map来实现它。

使用 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);

使用 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);

于 2022-01-17T05:58:14.980 回答
0

您可以使用for in loop;

第一个for in loop用于推question入主数组,第二个for in loop用于获取answer子对象

 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');
于 2022-01-17T05:50:02.533 回答