javascript-返回带有过滤子数组的父对象
作者:互联网
样本数据:
{
"QuestionId": 2,
"QuestionName": "Question2",
"QuestionTypeId": 2,
"QuestionTypeName": "CheckBoxList",
"Choices": [{
"ChoiceId": 7,
"ChoiceName": "Choice1",
"Answer": "7"
},
{
"ChoiceId": 8,
"ChoiceName": "Choice2",
"Answer": ""
},
{
"ChoiceId": 9,
"ChoiceName": "Choice3",
"Answer": ""
},
{
"ChoiceId": 10,
"ChoiceName": "Choice4",
"Answer": "10"
}
]
}
根据样本数据,如何使用Underscore或任何更好的javascript方法将过滤后的Choices保持相同的结构返回?根据Choice.Answer筛选Choice.答案必须有一个值.
解决方法:
如果您想用空白答案过滤掉选择,请使用Array.filter-我还假设您上面的数据结构在一个数组内(一个问题数组)
//Loop over each question
for (var i = 0; i < questions.length; i++) {
//For each question, filter the "Choices" array to not include empty Answers
questions[i].Choices = questions[i].Choices.filter(function(choice) {
return choice.Answer != ""
})
}
标签:nested-lists,multidimensional-array,underscore-js,javascript,jquery 来源: https://codeday.me/bug/20191120/2044297.html