Currently, I am dealing with data retrieved from an API that includes both title
and author
attributes (referred to as title_1
and title_2
in this case). To streamline the process of saving data to my database, I have set a condition where an item is deemed invalid if both title_1
and title_2
are empty.
While this method appears to work correctly for the author attribute, I keep encountering a scenario where an item is still saved even when title_1
is null
and title_2
is ""
. I suspect there might be an issue within how the values are being parsed.
Here is the JSON snippet of the problematic item:
"title_1": null,
"title_2": "",
Upon fetching and parsing the data, the following code is used:
request.get(apiUrl, function(error, response, body) {
if(!error && response.statusCode == 200) {
var data = JSON.parse(body);
callback(error, data.items);
}
});
Subsequently, the function removeInvalidItems(data);
is called which carries out the filtering process:
function removeInvalidItems(data) {
for (var i = 0; i < data.length; i++) {
if ( !isValid(data[i].title) && !isValid(data[i].title_2) ) {
data.splice(i, 1);
}
if ( !isValid(data[i].author) && !isValid(data[i].author_2) ) {
data.splice(i, 1);
}
}
return data;
};
The validity check is performed using the following logic:
function isValid(attr) {
if (attr === null || attr === '') {
return false;
} else return true;
};
If anyone has insights on why this particular item continues to pass through the isValid()
function as valid, please share your thoughts.