I have a few empty objects in my JSON request:
FXP:
"createdBy": {},
I would like to before the request is sent to the server convert these empty objects into following structure:
"createdBy": null,
How can I do it recursively in whole object please?
Example:
{
"main": {
"id": null,
"archived": true,
"createdBy": {},
"creationTime": null,
"location": {
"id": 79,
"address": {
"id": 79,
"city": null,
"latitude": 50.072613888888895,
"longitude": 14.543111111111111,
"street": null,
"streetNumber": null,
"district": null
},
"bsc": "BSC123",
"code": null,
"indoorOutdoor": null,
"siteId": "A0RST",
"stationType": {
"id": 1,
"name": "Indoor solution"
},
"shared": false,
"sapSacIrnCode": "31049.0",
"abloyLocation": "NA",
"name": "A0RST"
},
"actionName": {},
"orderType": {},
"project": {
"id": 1,
"cards": [],
"color": null,
"managerCustomer": null,
"managerSuntel": null,
"heliosSync": false,
"name": "Vodafone Test",
"parentProject": null,
"team": null,
"facility": {
"id": 1,
"code": 110,
"name": "110_MANAGEMENT"
},
"workers": []
},
"note": "",
"orderNumber": "2626262"
},
"milestoneSequence": {},
"milestones": []
}
To set all values in an object to null , pass the object to the Object. keys() method to get an array of the object's keys and use the forEach() method to iterate over the array, setting each value to null . After the last iteration, the object will contain only null values. Copied!
Null valuesJSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
Javascript. The null can not be assigned to undefined type variables: Javascript.
In JSON.parse
resp. JSON.stringify
you can pass a function as the 2nd argument.
This function gets name and value as arguments.
So you can adjust the values during parsing resp. stringifying.
Here is a recursive function that might help you:
function nullify (obj) {
for(key in obj) {
if(JSON.stringify(obj[key])=="{}") {
obj[key] = null;
} else if (typeof obj[key] == "object" && !Date.parse(obj[key])) {
obj[key] = nullify(obj[key]);
}
}
return obj;
}
for this example :
var obj = {
"b": 1,
"c": {},
"d": {
"a": 1,
"b": {},
"c": {
"x": 1,
"y": {}
}
}
}
the result of nullify(obj);
is
{
"b": 1,
"c": null,
"d": {
"a": 1,
"b": null,
"c": {
"x": 1,
"y": null
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With