javascript - Cleaning out bad JSON data from object? -
i retrieving building geolocation data service, in cases of data have missing properties.
good data
[{ "modifiedon": "2015-04-29 11:17:28.0", "buildingname": "wintefell", "latitude": "52.900619", "longitude": "-1.434602", "region": "the north", }, { "modifiedon": "2015-04-29 11:17:28.0", "buildingname": "water gardens", "latitude": "51.818051", "longitude": "-.354871", "region": "dorne" }]
bad data
missing region or building name
{ "modifiedon": "2015-04-29 11:17:28.0", "buildingname": "kings landing", "latitude": "23.818051", "longitude": "-.154871", }
after making ajax request store json response in object called _regionandbuildings
i want clean out bad data it, tried following code
console.log("starting size of building data : " + _regionandbuildings.length); //clean json setting object undefined (var = 0; < _regionandbuildings.length; i++) { if (_regionandbuildings[i].buildingname === undefined && _regionandbuildings[i].region === undefined) { console.log("deleting"); delete _regionandbuildings[i]; } } console.log("ending size of building data after cleaning : " + _regionandbuildings.length);
output
starting size : 209
delete x 17
ending size : 209
why code not removing bad elements in json object?
there 2 problems in code.
as per question
missing region or building name
you want remove elements of either region or building name missing. condition doesn't reflect that
if (_regionandbuildings[i].buildingname === undefined && _regionandbuildings[i].region === undefined)
since have used
&&
operator, when both expressions satisfied, code insideif
condition executed. so, need change logical or operator||
, thisif (_regionandbuildings[i].buildingname === undefined || _regionandbuildings[i].region === undefined)
when use
delete
operator on array, element in array deleted, index point nothing. means length of array not change. read more in this sectioninstead, can use
array.prototype.splice
, this_regionandbuildings.splice(i, 1);
but, prefer reconstructing array without elements don't want, array.prototype.filter
, this
var filteredbuildings = _regionandbuildings.filter(function (currentobject) { return currentobject.hasownproperty("buildingname") && currentobject.hasownproperty("region"); });
now, function passed run items in array , if function returns true
, object included in filtered result. so, if object has both buildingname
, region
properties, included in result.
note: prefer using object.hasownproperty
check if property exists in object, rather comparing value against undefined
, because if value of property undefined
, cannot differentiate between non-existing property , property value undefined
.
Comments
Post a Comment