How do I remove all null and empty string values from an object?
You're deleting sjonObj.key
, literally. You need to use array access notation:
delete sjonObj[key];
However, that will also delete where value is equal to 0, since you're not using strict comparison. Use ===
instead:
$.each(sjonObj, function(key, value){
if (value === "" || value === null){
delete sjonObj[key];
}
});
However, this will only walk the object shallowly. To do it deeply, you can use 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>
How do I remove all null and empty string values from an object in json java android from retrofit?
There are two ways
(1) While inflating the data you can filter these unwanted values
(2) Create a temporary list and add only required values from the main list.
sample code:
List<MainData> tempList = new ArrayList<>();
for(MainData data :postList)
{
if(null!= data.getName() && !data.getName().isEmpty())
{ tempList.add(data);
}
}
And then pass this tempList to the adapter.
Final code would look like this.
Api api = retrofit.create(Api.class);
Call<List<MainData>> call = api.getData();
call.enqueue(new Callback<List<MainData>>() {
@Override
public void onResponse (Call<List<MainData>> call, Response<List<MainData>> response) {
if (!response.isSuccessful()) {
Toast.makeText(MainActivity.this, response.code(), Toast.LENGTH_SHORT).show();
return;
}
List<MainData> postList = response.body();
//sort by ListId
Collections.sort(postList, (mainData, t1) -> mainData.getListId().compareTo(t1.getListId()));
// Filter out any items where "name" is blank or null.
List<MainData> tempList = new ArrayList<>();
for(MainData data :postList)
{
if(null!= data.getName() && !data.getName().isEmpty())
{ tempList.add(data);
}
}
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(MainActivity.this, tempList );
recyclerView.setAdapter(recyclerViewAdapter);
}
@Override
public void onFailure (Call<List<MainData>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Feel free to ask if something is unclear.
Remove empty elements from an array in Javascript
EDIT: This question was answered almost nine years ago when there were not many useful built-in methods in the Array.prototype
.
Now, certainly, I would recommend you to use the filter
method.
Take in mind that this method will return you a new array with the elements that pass the criteria of the callback function you provide to it.
For example, if you want to remove null
or undefined
values:
var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
var filtered = array.filter(function (el) { return el != null;});
console.log(filtered);
Remove empty & null values from nested object (ES6) - Clean nested Objects
Thanks to Nina Scholz, my enhanced version will be :
cleanObject = function(object) {
Object
.entries(object)
.forEach(([k, v]) => {
if (v && typeof v === 'object')
cleanObject(v);
if (v &&
typeof v === 'object' &&
!Object.keys(v).length ||
v === null ||
v === undefined ||
v.length === 0
) {
if (Array.isArray(object))
object.splice(k, 1);
else if (!(v instanceof Date))
delete object[k];
}
});
return object;
}
Related Topics
Input Date Format With Dd/Mm/Yyyy in the Input Field
How to Make New Line or Break in Array
Regex to Remove Certain Characters At the Beginning and End of a String
Jquery Ajax Post Results in 500 Internal Server Error
Check If Json Response Data Is Empty
Disable Chrome Strict Mime Type Checking
How to Play Audio File into Channel
Creating a Leaderboard in Html/Js
Is It Any Limit for Post Data Size in Ajax
How to Allow Only English Letters in Input Fields
How to Reload a Page With React-Router
How to Correctly Use Axios Params With Arrays
Automatically Force Mobile Browser to Desktop View
Regular Expression to Check Only One Decimal Point
Keep Selected Dropdown Result After Refreshing Page, Jquery
Jquery: Simplest Way to Check Url for a Parameter and Pass It to Anchor Href If It Exists
Using Html5/Javascript to Generate and Save a File
Add Two Numbers and Display Result in Textbox With JavaScript