admin管理员组文章数量:1417070
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": []
}
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": []
}
Share
Improve this question
edited Apr 7, 2022 at 19:18
Braiam
4,49611 gold badges49 silver badges83 bronze badges
asked Mar 20, 2015 at 14:17
redromredrom
11.6k34 gold badges166 silver badges269 bronze badges
3
- 1 May I ask why you want to do this? It might be easier to process server side. – Brian Glaz Commented Mar 20, 2015 at 14:20
- Could you provide some more context? How deep is everything nested? You can use Object.keys(your_object).forEach(callback) to loop over an object and then you can check Object.keys(sub_object) to see how many keys it has. If it has no keys you can set it to null. This could get very messy I think if you want to go very deep with this check.. – donnywals Commented Mar 20, 2015 at 14:20
- So this really has nothing to do with JSON right? You are just wanting to replace empty objects in your root object with null before even serializing to JSON correct? – Mike Brant Commented Mar 20, 2015 at 14:28
4 Answers
Reset to default 4In 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 don't like using strings too much:
function emptyObjToNull(object){
var isObject, hasKeys, isArray, current;
for(var k in object){
if(!object.hasOwnProperty(k))
return;
current = object[k];
isObject = typeof current == 'object';
hasKeys = isObject && Object.keys(current).length !== 0;
isArray = isObject && Object.prototype.toString.call(current) === "[object Array]";
if(hasKeys){
emptyObjToNull(current);
}else if(isArray){
for(var i = current.length; i--;){
emptyObjToNull(current);
}
}else if(isObject && !hasKeys){
object[k] = null; // Set the key directly, not the reference
}
}
}
Fiddle: http://jsfiddle/cfvm3r63/3/
Here is a solution using object-scan. Depending on your scenario using a dependency might make sense
// const objectScan = require('object-scan');
const data = {"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":[]};
const nullify = (input) => objectScan(['**'], {
rtn: 'count',
filterFn: ({ value, parent, property }) => {
if (
value instanceof Object
&& !Array.isArray(value)
&& Object.keys(value).length === 0
) {
parent[property] = null;
return true;
}
return false;
}
})(input);
console.log(nullify(data)); // returns number of changes
// => 4
console.log(data);
// => { main: { id: null, archived: true, createdBy: null, 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: null, orderType: null, 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: null, milestones: [] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/[email protected]"></script>
Disclaimer: I'm the author of object-scan
本文标签: javascriptHow to recursively set empty objectsto nullStack Overflow
版权声明:本文标题:javascript - How to recursively set empty objects {} to null? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745260211a2650322.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论