【问题标题】:return parent object with filtered child array返回具有过滤子数组的父对象
【发布时间】:2015-06-21 23:23:46
【问题描述】:

样本数据:

{
    "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"
        }
    ]
}

根据示例数据,如何通过使用下划线或任何更好的 javascript 方法保持相同结构的过滤选择返回?选择是根据 Choice.Answer 过滤的。答案必须有值。

【问题讨论】:

    标签: javascript jquery multidimensional-array underscore.js nested-lists


    【解决方案1】:

    如果您想过滤掉带有空白答案的选项,请使用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 != ""
        })
    }
    

    【讨论】:

    • 您的解决方案现在是我解决方案的一部分。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2017-10-07
    • 1970-01-01
    • 2016-05-14
    相关资源
    最近更新 更多