当前位置: 首页 > 面试题库 >

如何从json对象中删除所有null和空字符串值?

陆绍辉
2023-03-14
问题内容

您能告诉我如何从json对象中删除所有null和空字符串值吗?删除密钥时出现错误。

到目前为止,这是我所拥有的,但是不能正常工作:

$.each(sjonObj, function(key, value) {
    if(value == "" || value == null) {
        delete sjonObj.key;
    }
});



var sjonObj= {

  "executionMode": "SEQUENTIAL",

  "coreTEEVersion": "3.3.1.4_RC8",

  "testSuiteId": "yyy",

  "testSuiteFormatVersion": "1.0.0.0",

  "testStatus": "IDLE",

  "reportPath": "",

  "startTime": 0,

  "durationBetweenTestCases": 20,

  "endTime": 0,

  "lastExecutedTestCaseId": 0,

  "repeatCount": 0,

  "retryCount": 0,

  "fixedTimeSyncSupported": false,

  "totalRepeatCount": 0,

  "totalRetryCount": 0,

  "summaryReportRequired": "true",

  "postConditionExecution": "ON_SUCCESS",

  "testCaseList": [

    {

      "executionMode": "SEQUENTIAL",

      "commandList": [



      ],

      "testCaseList": [



      ],

      "testStatus": "IDLE",

      "boundTimeDurationForExecution": 0,

      "startTime": 0,

      "endTime": 0,

      "label": null,

      "repeatCount": 0,

      "retryCount": 0,

      "totalRepeatCount": 0,

      "totalRetryCount": 0,

      "testCaseId": "a",

      "summaryReportRequired": "false",

      "postConditionExecution": "ON_SUCCESS"

    },

    {

      "executionMode": "SEQUENTIAL",

      "commandList": [



      ],

      "testCaseList": [

        {

          "executionMode": "SEQUENTIAL",

          "commandList": [

            {

              "commandParameters": {

                "serverAddress": "www.ggp.com",

                "echoRequestCount": "",

                "sendPacketSize": "",

                "interval": "",

                "ttl": "",

                "addFullDataInReport": "True",

                "maxRTT": "",

                "failOnTargetHostUnreachable": "True",

                "failOnTargetHostUnreachableCount": "",

                "initialDelay": "",

                "commandTimeout": "",

                "testDuration": ""

              },

              "commandName": "Ping",

              "testStatus": "IDLE",

              "label": "",

              "reportFileName": "tc_2-tc_1-cmd_1_Ping",

              "endTime": 0,

              "startTime": 0,

              "repeatCount": 0,

              "retryCount": 0,

              "totalRepeatCount": 0,

              "totalRetryCount": 0,

              "postConditionExecution": "ON_SUCCESS",

              "detailReportRequired": "true",

              "summaryReportRequired": "true"

            }

          ],

          "testCaseList": [



          ],

          "testStatus": "IDLE",

          "boundTimeDurationForExecution": 0,

          "startTime": 0,

          "endTime": 0,

          "label": null,

          "repeatCount": 0,

          "retryCount": 0,

          "totalRepeatCount": 0,

          "totalRetryCount": 0,

          "testCaseId": "dd",

          "summaryReportRequired": "false",

          "postConditionExecution": "ON_SUCCESS"

        }

      ],

      "testStatus": "IDLE",

      "boundTimeDurationForExecution": 0,

      "startTime": 0,

      "endTime": 0,

      "label": null,

      "repeatCount": 0,

      "retryCount": 0,

      "totalRepeatCount": 0,

      "totalRetryCount": 0,

      "testCaseId": "b",

      "summaryReportRequired": "false",

      "postConditionExecution": "ON_SUCCESS"

    }

  ]

};



$.each(sjonObj, function(key, value) {

    if(value == "" || value == null) {

        delete sjonObj.key;

    }

});



console.log(sjonObj);


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

问题答案:

sjonObj.key实际上是要删除。您需要使用数组访问符号:

delete sjonObj[key];

但是,这也将删除value等于0的地方,因为您没有使用严格的比较。使用===来代替:

$.each(sjonObj, function(key, value){
    if (value === "" || value === null){
        delete sjonObj[key];
    }
});

但是,这只会使对象浅走。要深入地做,可以使用递归:

(function filter(obj) {
    $.each(obj, function(key, value){
        if (value === "" || value === null){
            delete obj[key];
        } else if (Object.prototype.toString.call(value) === '[object Object]') {
            filter(value);
        } else if ($.isArray(value)) {
            $.each(value, function (k,v) { filter(v); });
        }
    });
})(sjonObj);



var sjonObj = {

  "executionMode": "SEQUENTIAL",

  "coreTEEVersion": "3.3.1.4_RC8",

  "testSuiteId": "yyy",

  "testSuiteFormatVersion": "1.0.0.0",

  "testStatus": "IDLE",

  "reportPath": "",

  "startTime": 0,

  "durationBetweenTestCases": 20,

  "endTime": 0,

  "lastExecutedTestCaseId": 0,

  "repeatCount": 0,

  "retryCount": 0,

  "fixedTimeSyncSupported": false,

  "totalRepeatCount": 0,

  "totalRetryCount": 0,

  "summaryReportRequired": "true",

  "postConditionExecution": "ON_SUCCESS",

  "testCaseList": [

    {

      "executionMode": "SEQUENTIAL",

      "commandList": [



      ],

      "testCaseList": [



      ],

      "testStatus": "IDLE",

      "boundTimeDurationForExecution": 0,

      "startTime": 0,

      "endTime": 0,

      "label": null,

      "repeatCount": 0,

      "retryCount": 0,

      "totalRepeatCount": 0,

      "totalRetryCount": 0,

      "testCaseId": "a",

      "summaryReportRequired": "false",

      "postConditionExecution": "ON_SUCCESS"

    },

    {

      "executionMode": "SEQUENTIAL",

      "commandList": [



      ],

      "testCaseList": [

        {

          "executionMode": "SEQUENTIAL",

          "commandList": [

            {

              "commandParameters": {

                "serverAddress": "www.ggp.com",

                "echoRequestCount": "",

                "sendPacketSize": "",

                "interval": "",

                "ttl": "",

                "addFullDataInReport": "True",

                "maxRTT": "",

                "failOnTargetHostUnreachable": "True",

                "failOnTargetHostUnreachableCount": "",

                "initialDelay": "",

                "commandTimeout": "",

                "testDuration": ""

              },

              "commandName": "Ping",

              "testStatus": "IDLE",

              "label": "",

              "reportFileName": "tc_2-tc_1-cmd_1_Ping",

              "endTime": 0,

              "startTime": 0,

              "repeatCount": 0,

              "retryCount": 0,

              "totalRepeatCount": 0,

              "totalRetryCount": 0,

              "postConditionExecution": "ON_SUCCESS",

              "detailReportRequired": "true",

              "summaryReportRequired": "true"

            }

          ],

          "testCaseList": [



          ],

          "testStatus": "IDLE",

          "boundTimeDurationForExecution": 0,

          "startTime": 0,

          "endTime": 0,

          "label": null,

          "repeatCount": 0,

          "retryCount": 0,

          "totalRepeatCount": 0,

          "totalRetryCount": 0,

          "testCaseId": "dd",

          "summaryReportRequired": "false",

          "postConditionExecution": "ON_SUCCESS"

        }

      ],

      "testStatus": "IDLE",

      "boundTimeDurationForExecution": 0,

      "startTime": 0,

      "endTime": 0,

      "label": null,

      "repeatCount": 0,

      "retryCount": 0,

      "totalRepeatCount": 0,

      "totalRetryCount": 0,

      "testCaseId": "b",

      "summaryReportRequired": "false",

      "postConditionExecution": "ON_SUCCESS"

    }

  ]

};



(function filter(obj) {

    $.each(obj, function(key, value){

        if (value === "" || value === null){

            delete obj[key];

        } else if (Object.prototype.toString.call(value) === '[object Object]') {

            filter(value);

        } else if (Array.isArray(value)) {

            value.forEach(function (el) { filter(el); });

        }

    });

})(sjonObj);



console.log(sjonObj)


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

请注意,如果您愿意使用lodash /
underscore.js之类的库,则可以_.pick改用。但是,由于两个库都没有提供深层过滤功能,因此您仍然需要使用递归进行深层过滤。

sjonObj = (function filter(obj) {
    var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });
    return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });
})(sjonObj);

此变体具有保留原始对象不变的附加优点,但是它确实创建了一个全新的副本,如果您不需要原始对象,效率将会降低。

var sjonObj = {

  "executionMode": "SEQUENTIAL",

  "coreTEEVersion": "3.3.1.4_RC8",

  "testSuiteId": "yyy",

  "testSuiteFormatVersion": "1.0.0.0",

  "testStatus": "IDLE",

  "reportPath": "",

  "startTime": 0,

  "durationBetweenTestCases": 20,

  "endTime": 0,

  "lastExecutedTestCaseId": 0,

  "repeatCount": 0,

  "retryCount": 0,

  "fixedTimeSyncSupported": false,

  "totalRepeatCount": 0,

  "totalRetryCount": 0,

  "summaryReportRequired": "true",

  "postConditionExecution": "ON_SUCCESS",

  "testCaseList": [

    {

      "executionMode": "SEQUENTIAL",

      "commandList": [



      ],

      "testCaseList": [



      ],

      "testStatus": "IDLE",

      "boundTimeDurationForExecution": 0,

      "startTime": 0,

      "endTime": 0,

      "label": null,

      "repeatCount": 0,

      "retryCount": 0,

      "totalRepeatCount": 0,

      "totalRetryCount": 0,

      "testCaseId": "a",

      "summaryReportRequired": "false",

      "postConditionExecution": "ON_SUCCESS"

    },

    {

      "executionMode": "SEQUENTIAL",

      "commandList": [



      ],

      "testCaseList": [

        {

          "executionMode": "SEQUENTIAL",

          "commandList": [

            {

              "commandParameters": {

                "serverAddress": "www.ggp.com",

                "echoRequestCount": "",

                "sendPacketSize": "",

                "interval": "",

                "ttl": "",

                "addFullDataInReport": "True",

                "maxRTT": "",

                "failOnTargetHostUnreachable": "True",

                "failOnTargetHostUnreachableCount": "",

                "initialDelay": "",

                "commandTimeout": "",

                "testDuration": ""

              },

              "commandName": "Ping",

              "testStatus": "IDLE",

              "label": "",

              "reportFileName": "tc_2-tc_1-cmd_1_Ping",

              "endTime": 0,

              "startTime": 0,

              "repeatCount": 0,

              "retryCount": 0,

              "totalRepeatCount": 0,

              "totalRetryCount": 0,

              "postConditionExecution": "ON_SUCCESS",

              "detailReportRequired": "true",

              "summaryReportRequired": "true"

            }

          ],

          "testCaseList": [



          ],

          "testStatus": "IDLE",

          "boundTimeDurationForExecution": 0,

          "startTime": 0,

          "endTime": 0,

          "label": null,

          "repeatCount": 0,

          "retryCount": 0,

          "totalRepeatCount": 0,

          "totalRetryCount": 0,

          "testCaseId": "dd",

          "summaryReportRequired": "false",

          "postConditionExecution": "ON_SUCCESS"

        }

      ],

      "testStatus": "IDLE",

      "boundTimeDurationForExecution": 0,

      "startTime": 0,

      "endTime": 0,

      "label": null,

      "repeatCount": 0,

      "retryCount": 0,

      "totalRepeatCount": 0,

      "totalRetryCount": 0,

      "testCaseId": "b",

      "summaryReportRequired": "false",

      "postConditionExecution": "ON_SUCCESS"

    }

  ]

};



sjonObj = (function filter(obj) {

    var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });

    return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });

})(sjonObj);



console.log(sjonObj);


<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>


 类似资料:
  • 我如何从JSON Java android中的对象中删除所有空和空字符串值? 过滤掉“name”为空或空的任何项目。 这是我的主要activity 这是我的助手 } 这是数据 公共类MainData{ } 这是Api } 这是我的应用程序,我想删除零和emp输入图像描述在这里

  • 问题内容: 如何删除python字符串中的所有空格?例如,我希望将一个字符串转换为,但是我似乎无法通过以下方式完成此操作: 问题答案: 利用没有sep参数的str.split的行为: 如果只想删除空格而不是所有空格: 过早优化 尽管效率不是主要目标(编写清晰的代码是),但以下是一些初始时间: 请注意,正则表达式已缓存,因此它没有您想象的那么慢。编译事前帮助一些,但在实践中,如果你把这个只会重要 很

  • 问题内容: 我有课 它具有几个属性,可以说10。在这10个中,有3个填充了剩余的数据,其中7个是blank.ie空字符串“”使用此链接作为参考。我只想显示NON-NULL和NON- EMPTY字符串属性。但是最终输出具有所有10个属性。我只想看3。 } 我也尝试过 作为属性。没运气。我也这样 其中“ usr”是用户实例。运气不好,我的意思是,所有10个属性都返回“ t” 如您所见,仅填充了用户ID

  • 问题内容: 我在textarea中有一个文本,我使用.value属性将其读出。 现在,我想使用正则表达式.replace从我的文本中删除所有换行符(按时产生的字符),但是如何在正则表达式中指示换行符? 如果那不可能,还有另一种方法吗? 问题答案: 这可能是一个常见问题解答。无论如何,换行符(更好的是:换行符)可以是回车符(在较旧的Mac上为CR,),换行符(在Unices 包括Linux上为LF,

  • 我在textarea中有一个文本,我使用.value属性读出它。 现在我想从我的文本中删除所有的换行符(按Enter时产生的字符),现在使用.替换为正则表达式,但如何在正则表达式中指示换行符? 如果不可能的话,是否还有其他方法?

  • 问题内容: 我需要从字符串中删除所有特殊字符,标点符号和空格,以便只有字母和数字。 问题答案: 这可以不用正则表达式来完成: 您可以使用: 如果您坚持使用正则表达式,则其他解决方案也可以。但是请注意,如果可以在不使用正则表达式的情况下完成此操作,那么这是最好的解决方法。