Comment supprimer toutes les valeurs de chaîne nulles et vides d'un objet json?


user1542984:

Pouvez-vous s'il vous plaît me dire comment supprimer toutes les valeurs de chaîne nulles et vides d'un objet json? J'obtiens une erreur lors de la suppression de la clé.

C'est ce que j'ai jusqu'à présent, mais cela ne fonctionne pas correctement:

$.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>

Alexis King:

Vous supprimez sjonObj.key, littéralement. Vous devez utiliser la notation d'accès au tableau:

delete sjonObj[key];

Cependant, cela supprimera également où la valeur est égale à 0, car vous n'utilisez pas de comparaison stricte. Utilisez à la ===place:

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

Cependant, cela ne marchera que peu profondément. Pour le faire en profondeur, vous pouvez utiliser la récursivité:

(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>


Notez que si vous souhaitez utiliser une bibliothèque comme lodash / underscore.js, vous pouvez utiliser à la _.pickplace. Cependant, vous devrez toujours utiliser la récursivité pour filtrer en profondeur, car aucune des deux bibliothèques ne fournit une fonction de filtre profond.

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);

Cette variante a l'avantage supplémentaire de ne pas modifier l'objet d'origine, mais elle crée une copie entièrement nouvelle, ce qui serait moins efficace si vous n'avez pas besoin de l'objet d'origine.

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>

Articles connexes