3 回答
TA贡献1890条经验 获得超9个赞
Array.prototype.filter()
完全符合目的:
const src = [{question:'blah blah blah ?',response:'blah blah blah',isCorrect:true,isEssayQuestion:false},{question:'blah blah blah blah',response:'blah blah blah',isCorrect:true,isEssayQuestion:false},{question:'blah blah blah ?',response:'blah blah blah blah',isCorrect:true,isEssayQuestion:true},{question:'True or False: I am new to JS.',response:'True',isCorrect:true,isEssayQuestion:false}],
filterQuestionsByType = (submissions, essayquestions) =>
submissions.filter(({isEssayQuestion}) => isEssayQuestion == essayquestions)
console.log(filterQuestionsByType(src, true))
TA贡献1895条经验 获得超7个赞
那么就使用.filter这个案例的方法
const submissions = [
{
question: 'blah blah blah ?',
response: 'blah blah blah',
isCorrect: true,
isEssayQuestion: false
},
{
question: 'blah blah blah blah',
response: 'blah blah blah',
isCorrect: true,
isEssayQuestion: false
},
{
question: 'blah blah blah ?',
response: 'blah blah blah blah',
isCorrect: true,
isEssayQuestion: true
},
{
question: 'True or False: I am new to JS.',
response: 'True',
isCorrect: true,
isEssayQuestion: false
}
];
function essays(essay, question) {
return essay.filter(({isEssayQuestion}) => isEssayQuestion === question)
}
console.log(essays(submissions, false));
console.log("------------------------------------");
console.log(essays(submissions, true));
TA贡献1820条经验 获得超9个赞
这是另一种方法。您可以简单地将源数组映射到新对象属性 (sortedValues) 并将结果写入其中。此方法只运行一次,而不是其他示例,您需要运行两次 - 真和假。
const submissions = [
{
question: 'blah blah blah ?',
response: 'blah blah blah',
isCorrect: true,
isEssayQuestion: false
},
{
question: 'blah blah blah blah',
response: 'blah blah blah',
isCorrect: true,
isEssayQuestion: false
},
{
question: 'blah blah blah ?',
response: 'blah blah blah blah',
isCorrect: true,
isEssayQuestion: true
},
{
question: 'True or False: I am new to JS.',
response: 'True',
isCorrect: true,
isEssayQuestion: false
}
];
const sortedValues = {
trueValues: [],
falseValues: []
}
submissions.map(item => {
sortedValues[`${item.isEssayQuestion}Values`] = [...sortedValues[`${item.isEssayQuestion}Values`], item]
})
console.log(JSON.stringify(sortedValues, 2,2))
添加回答
举报