Check Json If Has Nested Object
How can I check if subproducts object exists in my JSON? 'products':[ { 'id':5002, 'description':'i dont know', 'position':1, 'weight':1, 'subproducts':{
Solution 1:
I think you should try this:
products[0].hasOwnProperty('subproducts')
Solution 2:
It appears that when you say subproducts doesn't exist, it does actually exist as an object, but with no properties. An object with no properties is still considered truthy in JavaScript, so that's why it always passes your truthy condition, and then throws the undefined error if you try to access the name
property.
Example:
var obj = {};
console.log(obj ? true : false); // true
In this case you can test for the name
existing:
$.each(company.products, function (j, product) {
if(product.hasOwnProperty('subproducts') {
if(product.subproducts.name){
// it has subproducts AND the subproduct.name exists
}
} else {
// do this
}
}
Solution 3:
Your best bet would be to go through the object and check for an object:
functionhasSubObject(products) {
for(var key in products){
if(!products.hasOwnProperty(key))continue;
if(typeof products[key] === "object") returntrue;
}
returnfalse;
}
Which is gross and will probably slow down if you have large objects
Post a Comment for "Check Json If Has Nested Object"