0

How can I check if subproducts object exists in my JSON?

"products":[ { "id":5002, "description":"i dont know", "position":1, "weight":1, "subproducts":{ "name":"test", "description":"description of test" } } ], 

It keeps me returning true whenever I use if(product.subproducts) and product.subproduct.name, which cannot read name property undefined.

$.each(company.products, function (j, product) { if(product.hasOwnProperty('subproducts') { //do something } else { // do this } } 

UPDATED: forgot to say that, for each products, contains subproducts or not.

10
  • what do you get when you log the output of typeof(products.subproducts); ? Commented Jul 1, 2014 at 14:43
  • it gives me undefined. Commented Jul 1, 2014 at 14:45
  • 1
    "It keeps me returning true whenever I use if(product.subproducts) or product.subproduct.name, which cannot read name property undefined." How can you get true if the code throws an error? Commented Jul 1, 2014 at 14:47
  • 2
    You do realize that product.subproducts is not the same as product.subproduct? Accessing product.subproduct.name is very wrong. Commented Jul 1, 2014 at 14:49
  • 1
    You have an object that contains an array of objects. So products.subproducts isn't right, it should be products[0].subproducts Commented Jul 1, 2014 at 14:50

3 Answers 3

1

I think you should try this:

products[0].hasOwnProperty('subproducts')

Sign up to request clarification or add additional context in comments.

2 Comments

You're right. Products is an array of objects. OP has to iterate to check every object for a subproduct key.
The OP is already doing that: if(product.hasOwnProperty('subproducts') {
0

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 } } 

Comments

-1

Your best bet would be to go through the object and check for an object:

function hasSubObject(products) { for(var key in products){ if(!products.hasOwnProperty(key))continue; if(typeof products[key] === "object") return true; } return false; } 

Which is gross and will probably slow down if you have large objects

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.