简体   繁体   中英

Check to see if child object exists in JavaScript object

In JavaScript, I am building an object. Inside a loop I need to check to see if the root object already contains a child object, and if not, I need to add it.

childObjectName = this.name.split('.')[1];

Now, how do I check to see if my root object, myObject already contains a child by the name of whatever is contained in childObjectName ?

EDIT:

I think perhaps my OP wasn't very clear. Sorry about that.

Let's say childObjectName ends up having a value of "ThisName". Now, I want to check and see if myObject already contains a child object called "ThisName". And as this is in a loop, I need to be able to check for ANY name.

I hope that makes more sense?

EDIT 2:

{  
   "myObject":{  
      "CampaignType":{  
         "Exclusive":25,
         "Shared":6
      }
   }
}

Ok, now, let's say the var childObjectName is equal to "CampaignType". In this case, I need to get TRUE when looing to see if myObject contains childObjectName .

But, let's say childObjectName is equal to "FooBar". In that case, I would need to get FALSE.

Something like this. If a property doesn't exist in the object it returns undefined . So, you basically needs to check if the Property exists on the object or not.

if(! myObject[childObjectName])
{
  myObject.childObjectName = this.name.split('.')[1];
}

You should use hasOwnProperty . It's compatible with all browsers, and it works even when the property has a falsy value, such as null , false , etc.

 var myObject = { propOne: "hello world", propTwo: false, CampaignType: { "Exclusive": 25, "Shared": 6 } }; checkForPropertyName("prop" + "One"); checkForPropertyName("propTwo"); checkForPropertyName("propThree"); checkForPropertyName("CampaignType"); function checkForPropertyName(childObjectName) { if (myObject.hasOwnProperty(childObjectName)) { console.log('myObject has property "' + childObjectName + '"'); } else { console.log('myObject does NOT have property "' + childObjectName + '"'); } } 

childObjectName = childObjectName || this.name.split('.')[1];

If the property exists (and its value is truthy) its value will not change, otherwise it will be given a value. This can be applied to properties of root.

Note that this may not work if the property exists and it has a falsy value.

Update for edit: If you need to to this for an arbitrary property and your code runs at the root level, then use this to refer to root:

Object.getOwnPropertyNames(this); // Now you have an array of properties set on root.
var childObjectName = this.name.split('.')[1];
if(myobject[childobjectName]){
   //the child object is present
 }else{
 //the child object is not present
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM