gpt4 book ai didi

javascript - 解构嵌套对象 es6

转载 作者:行者123 更新时间:2023-12-04 17:11:49 25 4
gpt4 key购买 nike

你还好吗?我想从嵌套对象中删除一个属性(“isCorrect”)。

原始列表

    id: 1,
questionText: 'This is a test question for tests',
answerOptions: [
{
answerText: 'A',
isCorrect: true
},
{
answerText: 'B',
isCorrect: false
}
],
difficulty: 1
},
{
id: 2,
questionText: 'This is another test question for tests',
answerOptions: [
{
answerText: 'A',
isCorrect: false
},
{
answerText: 'B',
isCorrect: true
}
],
difficulty: 2
}

预期结果

    id: 1,
questionText: 'This is a test question for tests',
answerOptions: [
{
answerText: 'A'
},
{
answerText: 'B'
}
],
difficulty: 1
},
{
id: 2,
questionText: 'This is another test question for tests',
answerOptions: [
{
answerText: 'A'
},
{
answerText: 'B'
}
],
difficulty: 2
}

我设法使用下面的删除代码,但这不是最好的方法

const cleanResponses = (questions: Question[]): Question[] => {
questions.forEach(question => {
question.answerOptions.forEach((answer) => {
delete answer.isCorrect
});
})

return questions;
}

试过下面的行但没有成功:(

const { answerOptions: [{ isCorrect }], ...rest } = 问题

谢谢

最佳答案

使用 Array#map :

const arr = [
{ id: 1,
questionText: 'This is a test question for tests',
answerOptions: [ { answerText: 'A', isCorrect: true }, { answerText: 'B', isCorrect: false } ],
difficulty: 1
},
{
id: 2,
questionText: 'This is another test question for tests',
answerOptions: [ { answerText: 'A', isCorrect: false }, { answerText: 'B', isCorrect: true } ],
difficulty: 2
}
];

const res = arr.map(({ answerOptions = [], ...elem }) => ({
...elem,
answerOptions: answerOptions.map(({ isCorrect, ...answer }) => answer)
}));

console.log(res);

关于javascript - 解构嵌套对象 es6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69288399/

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