gpt4 book ai didi

reactjs - 如何通过 lodash 对嵌套/复杂对象使用 reduce 方法

转载 作者:行者123 更新时间:2023-12-05 04:37:14 24 4
gpt4 key购买 nike

我有这样的数据

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

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

最佳答案

您只能使用 Javascript 使用 Object.values 来实现它和 Array.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);

关于reactjs - 如何通过 lodash 对嵌套/复杂对象使用 reduce 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70736857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com