1

The values for "A" & "B" equal "Value" however the value for "C" equals [object Object]:

{ "A": "Value", "B": "Value", "C": { "I": "Value", "II": "Value" } } 

I have a loop and would like to add an IF to check whether the value is equal to an [object Object], ie; has more than one field within.

What is the best way to achieve this?

1
  • I have a loop - show that loopCommentedApr 15, 2017 at 19:39

4 Answers 4

2

Easiest would be to use typeof x where x is whatever you are checking. For "A" and "B" it would be "string" and for "C" it would be "object".

    1

    You could just transform each value into a string with .toString() function and check the result. If given value is an object - nested, single or even empty - it will return "[object Object]".

    Note: It will work even if a given value is string, number, boolean or array.

    var obj = { "A": "Value", "B": true, "C": { "I": "Value", "II": "Value", "III": {foo: 'bar'}, "IV": {}, "V": 'foo' }, "D": 24, "E": ['hi'] }; for (var key in obj) { if (obj[key].toString() != "[object Object]" ) { console.log(obj[key]); } else { console.log("It's an object"); } }

      1

      Check out this page on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

      It describes the typeof operator.

      if(typeof obj === 'object') { ... } else if(typeof obj === 'string') { ... } 
      0
        0
         let test = { "first": "fetr", "second": { "edwr":12, "ewrgtr":32 } }; Object.keys(test).forEach(function (key) { if(typeof test[key] === 'object'){ console.log(key,test[key]); } }); 

        This works as of ECMAscript 5 :)

          Start asking to get answers

          Find the answer to your question by asking.

          Ask question

          Explore related questions

          See similar questions with these tags.