I am trying to remove the empty object {} from the below structure.
JavaScript
x
17
17
1
data = [{
2
"total" : "value",
3
"status" : "statusVal",
4
"recs" : [{
5
"total" : "value",
6
"region" : "name",
7
"recs" : [{},{
8
"recs" : [{
9
"recs" : [{
10
"value" : "a",
11
"label" : "fn"
12
}]
13
}]
14
}]
15
}]
16
}]
17
This is my JavaScript code where I process the data and trying to remove the empty object from the result.
JavaScript
1
25
25
1
var result = json.parse(data);
2
for(var i=0;i<result.length;i++){
3
if(result[i].hasOwnProperty("recs")){
4
var fset = result[i].recs;
5
for(var j=0;j<fset.length;j++){
6
if(fset[j].recs === undefined || fset[j].recs === null){
7
delete fset[j].recs;
8
}
9
if(fset[j].hasOwnProperty("recs")){
10
var sset = fset[i].recs;
11
for(var k=0;k<sset.length;k++){
12
var tset = sset[i].recs;
13
if(sset[k].hasOwnProperty("recs")){
14
for(var z=0;z<tset.length;z++){
15
if(tset[z].hasOwnProperty("recs")){
16
// logic to push
17
}
18
}
19
}
20
}
21
}
22
}
23
}
24
}
25
I tried checking null and undefined and also with property check bool as false. Since the empty {} is always returning length as 1, that is also ruled out. I am stuck here on processing the removal of empty object.
Above code is removing the entire recs node. Can you help me find what I am missing?
Advertisement
Answer
Check the length of the Object.keys()
to see if object is empty or not.
JavaScript
1
2
1
Object.keys(fset[j].recs).length === 0
2
You can’t iterate all the dynamic levels of array manually, so better to write the function which has recursive function call.
JavaScript
1
27
27
1
var data = [{
2
"total": "value",
3
"status": "statusVal",
4
"recs": [{
5
"total": "value",
6
"region": "name",
7
"recs": [{}, {
8
"recs": [{
9
"recs": [{
10
"value": "a",
11
"label": "fn"
12
}]
13
}]
14
}]
15
}]
16
}]
17
18
function removeEmpty(ary) {
19
ary.forEach((item, index) => {
20
if (Object.keys(item).length === 0) { ary.splice(index, 1); }
21
else if (item.recs && item.recs.length > 0)
22
removeEmpty(item.recs)
23
});
24
}
25
26
removeEmpty(data)
27
console.log(data)