3

I am trying to see if the property contains another object.

I have this:

{
  "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.

James
  • 693
  • 1
  • 13
  • 27

4 Answers4

3

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)
  }
}
zennith
  • 410
  • 2
  • 5
  • 17
2

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")
}
if (typeof yourobject.prop5=='object'){
}
Vlado Pandžić
  • 4,879
  • 8
  • 44
  • 75
2

Try with typeof() method and Object.values

  1. Object.values create the array for values and Array.map() recreate array the with condition typeof(a) == 'object'

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)
prasanth
  • 22,145
  • 4
  • 29
  • 53
2

You can use typeof function which 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]));

})
Vineesh
  • 3,762
  • 20
  • 37