Search code examples
node.jsjsonhasownproperty

Node JS - Check if JSON File hasOwnProperty with nested elements


im simply trying to check if a JSON Object has a specific key. First i parse the JSON File to an object but when i try this:

  console.log("Inspect:" + util.inspect(oldConfig[websiteName][groupName]));
  console.log("Check Prop: " + oldConfig.hasOwnProperty([websiteName][groupName]));

my console says this:

Inspect:{ tmpTestTitle: { active: false, fileName: 'tmpFilename1' } }
Check Prop: false

Im wondering why i can see the key and value by using util.inspect, but can't when i try to check with hasOwnProperty-function.

I also checked the correct formatting of the JSON-File and tried to reach the key with the dot notations ( websiteName.groupName ).

For supplementation, this is how the whole json-object looks like in the console:

{ tmpWebTitle: { tmpGroupname: { tmpTestTitle: [Object] } } }

Thanks for your help.


Solution

  • Object.hasOwnProperty() takes string as parameter and checks in the keys of object, not in the keys of nested object.

    For your problem you should first access the inner value and check hasOwnProperty() on it

    oldConfig[websiteName].hasOwnProperty(groupName));
    

    let oldConfig={ 
                  tmpWebTitle: { 
                                 tmpGroupname: {
                                  tmpTestTitle: [] 
                                 } 
                               } 
    
                   };
    
    let websiteName ='tmpWebTitle';
    let groupName ='tmpGroupname';
    console.log("Check prop:", oldConfig[websiteName].hasOwnProperty(groupName));
    .as-console-wrapper { max-height: 100% !important; top: 0; }