midhun k midhun k - 1 month ago 15
Javascript Question

check null or undefined value for array?

I have an array in the following format and i have to check whether there is any null or undefined value

[{
"categoryName": "A",
"product": [{
"catogoryName": "A",
"price": "10",
"productName": "a"
}, {
"catogoryName": "A",
"price": "100",
"productName": "a2"
}, {
"catogoryName": "A",
"price": "5654",
"productName": "dfhdh"
}, {
"catogoryName": "A",
"price": "572",
"productName": "d"
}]
}, {
"categoryName": "B",
"product": [{
"catogoryName": "B",
"price": "10",
"productName": "b"
}, {
"catogoryName": "B",
"price": "300",
"productName": "b2"
}]
}]


I have tried with the following code, but it always gives me
success:1
message.

var validateCategoryList = function (categoryList,callback) {
async.eachSeries(categoryList, function (categoryChunk, callback) {
var categoryName = categoryChunk.categoryName;
var productList = categoryChunk.product;
console.log(categoryName);
if(!(categoryName == null || categoryName == undefined)){
async.eachSeries(productList, function (item, callback) {
var productName = item.productName;
var price = item.price;
console.log(productName);
console.log(price);
if((!(productName == null || price == undefined)) || (!(productName == null || price == undefined))){
callback(null);
}
else{
callback({'success':'0','result':{},'errorMessage':'CategoryLIst invalid'})
return;
}
},function (err) {
callback(null);
});
}
else{
callback({'success':'0','result':{},'errorMessage':'CategoryLIst invalid'})
return;
}
},function (err) {
callback({'success':'1'})
});

}

Answer Source

Use the callback to JSON.stringify as a poor-man's way to traverse the object:

function hasNull(obj) {
  let result = false;

  JSON.stringify(obj, (_, v) => v === null || v === undefined ? result = true : v);

  return result;
}