Check if an object exists in a property

I am trying to check if a property contains another object.

I have it:

{
  "prop1": "value",
  "prop2": "value",
  "prop4": "value",
  "prop5": {
      "innerprop1": "value",
      "innerprop2": "value"
  },
  "prop6": {
      "innerprop3": "value",
      "innerprop4": "value"
  }
}

      

I want to know if any of the properties has an object in it.

Any help would be appreciated.

+3


source to share


4 answers


Please check prop7



obj = {
  "prop1": "value",
  "prop2": "value",
  "prop4": "value",
  "prop5": {
      "innerprop1": "value",
      "innerprop2": "value"
  },
  "prop6": {
      "innerprop3": "value",
      "innerprop4": "value"
  },
  "prop7": [] // Also an object!
}

for(var key in obj) {

  if(typeof obj[key] === 'object') {
    console.log(key)
  }
}
      

Run codeHide result


+3


source


var yourObject={
  "prop1": "value",
  "prop2": "value",
  "prop4": "value",
  "prop5": {
      "innerprop1": "value",
      "innerprop2": "value"
  },
  "prop6": {
      "innerprop3": "value",
      "innerprop4": "value"
  }
}

if(typeof yourObject.prop5=='object'){
console.log("It is object")
}
      

Run codeHide result




if (typeof yourobject.prop5=='object'){
}

      

+2


source


Try typeof()

andObject.values

var arr ={ "prop1": "value", "prop2": "value", "prop4":"value", "prop5": { "innerprop1": "value","innerprop2": "value" }, "prop6": { "innerprop3":"value", "innerprop4": "value" } }

//returning the keyname
console.log(Object.keys(arr).filter(a=> typeof(arr[a]) == 'object' ))

var res = Object.values(arr).map(function(a){
return typeof(a) == 'object'
})

console.log(res)
      

Run codeHide result


+2


source


You can use a function typeof

that will return object

for objects

var json = '{ "prop1": "value", "prop2": "value", "prop4": "value", "prop5": { "innerprop1": "value", "innerprop2": "value" }, "prop6": { "innerprop3": "value", "innerprop4": "value" } }';
jsonObject = JSON.parse(json);
var keys = Object.keys(jsonObject);
keys.forEach(function(element){
  console.log(typeof(jsonObject[element]));

})

      

+2


source







All Articles