4

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.

1
  • obj[property].Constructor === Object does the trick Commented Jul 26, 2017 at 12:10

4 Answers 4

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

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

Comments

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'){
}

Comments

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)

Comments

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]));

})

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.