使用 javascript 删除 json 部分时删除 Null 值

Remove Null value when delete a json portion using javascript

我下面有一个 json 对象。如果问题值为空,我想删除一部分。所以根据下面 json 我需要删除 id=7602 部分。

 [   {
                "id": 9333,
                "component": "question_pool",
                "sub_comp_arr": [
                    {
                        "id": 7769,
                        "component": "question",
                        "sub_comp_arr": [
                            {
                                "id": 2552,
                                "component": "question_segment",
                                "value": "Answer1"
                            },
                            {
                                "id": 1011,
                                "component": "question_segment",
                                "value": "Answer2"
                            },
                            {
                                "id": 8691,
                                "component": "question_segment",
                                "value": "Answer3"
                            }
                        ],
                        "type": "single_choice",
                        "value": "<p>Question1?</p>\n"
                    },
                    {
                        "id": 7602,
                        "component": "question",
                        "sub_comp_arr": [
                            {
                                "id": 921,
                                "component": "question_segment",
                                "value": ""
                            }
                        ],
                        "type": "single_choice",
                        "value": ""
                    }
                ]
            },{...}
    ]

我已经实现了下面的代码

    var y= content_json.content_arr;
    var keyCount  = Object.keys(y).length;
    for (var i = 0; i < keyCount; i++) {    
        var questionCount = (content_json.content_arr[i]['sub_comp_arr']).length;
        for (let j = 0; j < questionCount; j++){    
          var emptyquestion= ((content_json.content_arr[i]['sub_comp_arr'][j]['value']).trim()).length;
          if (emptyquestion===0){
            delete (content_json.content_arr[i]['sub_comp_arr'][j]);
}
    
    }
        
    }

但问题是如果我使用 delete (content_json.content_arr[i]['sub_comp_arr'][j]); 它会在我的 Json 上保存一个空值,这是我不想要的。如何实现

您可以改用过滤器。

content_json.content_arr[i].sub_comp_arr = content_json.content_arr[i].sub_comp_arr.filter(q => q.value)