如何从json对象中删除所有空值和空string值?
你能告诉我如何从json对象中删除所有null和空string值吗? 我在删除密钥时出错。
这是我到目前为止,但它不能正常工作:
$.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];
但是,这也将删除值等于0,因为你没有使用严格的比较。 改用===
:
$.each(sjonObj, function(key, value){ if (value === "" || value === null){ delete sjonObj[key]; } });
但是,这只会轻微地走动对象。 为了做到这一点,你可以使用recursion:
(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>
使用一些ES6 / ES2015 :
如果你不想创build一个额外的function,并删除项目“内联”。
Object.keys(obj).forEach(k => (!obj[k] && obj[k] !== undefined) && delete obj[k]);
jsbin
同样,写作一个function。
const removeEmpty = (obj) => { Object.keys(obj).forEach((k) => (!obj[k] && obj[k] !== undefined) && delete obj[k]); return obj; };
jsbin
这个函数也使用recursion从嵌套对象中删除项目:
const removeEmpty = (obj) => { Object.keys(obj).forEach(k => (obj[k] && typeof obj[k] === 'object') && removeEmpty(obj[k]) || (!obj[k] && obj[k] !== undefined) && delete obj[k] ); return obj; };
jsbin
与之前的function相同,但使用ES7 / 2016 Object.entries
:
const removeEmpty = (obj) => { Object.entries(obj).forEach([key, val] => (val && typeof val === 'object') && removeEmpty(val) || (!val && val !== undefied) && delete obj[k] ); return obj; };
和第三个例子一样,但是在ES5中 :
function removeEmpty(obj) { Object.keys(obj).forEach(function(key) { (obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) || (obj[key] === '' || obj[key] === null) && delete obj[key] }); return obj; };
jsbin
您需要使用括号表示法,因为key
是一个将键保存为值的variables
$.each(sjonObj, function(key,value){ // console.log(value); if(value==""||value==null){ delete sjonObj[key]; } });
delete sjonObj.key
从delete sjonObj.key
删除名为key
的属性,而不是你需要使用key
作为一个variables来保存属性名称。
注意:它仍然不会处理嵌套的对象
var data = [{ "name": "bill", "age": 20 }, { "name": "jhon", "age": 19 }, { "name": "steve", "age": 16 }, { "name": "larry", "age": 22 }, null, null, null]; //eliminates all the null valued JSONs from the data data = data.filter(function(x) { return x !== null }); console.log("data: " + JSON.stringify(data));
这里是优化的代码片段,以删除空的数组/对象:
function removeNullsInObject(obj) { if( typeof obj === 'string' ){ return; } $.each(obj, function(key, value){ if (value === "" || value === null){ delete obj[key]; } else if ($.isArray(value)) { if( value.length === 0 ){ delete obj[key]; return; } $.each(value, function (k,v) { removeNullsInObject(v); }); } else if (typeof value === 'object') { if( Object.keys(value).length === 0 ){ delete obj[key]; return; } removeNullsInObject(value); } }); }
谢谢@亚历克斯国王:)
function removeAllBlankOrNull(JsonObj) { $.each(JsonObj, function(key, value) { if (value === "" || value === null) { delete JsonObj[key]; } else if (typeof(value) === "object") { JsonObj[key] = removeAllBlankOrNull(value); } }); return JsonObj; }
以recursion方式删除所有空string和空值。 小提琴
build立在suryaPavan的答案这个微小的修改可以清除对象或数组内的invidival emptys后的空对象。 这可以确保您没有空的数组或对象。
function removeNullsInObject(obj) { if( typeof obj === 'string' || obj === "" ){ return; } $.each(obj, function(key, value){ if (value === "" || value === null){ delete obj[key]; } else if ($.isArray(value)) { if( value.length === 0 ){ delete obj[key]; return; } $.each(value, function (k,v) { removeNullsInObject(v); }); if( value.length === 0 ){ delete obj[key]; } } else if (typeof value === 'object') { if( Object.keys(value).length === 0 ){ delete obj[key]; return; } removeNullsInObject(value); if( Object.keys(value).length === 0 ){ delete obj[key]; } } }); }