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 loop Commented Apr 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".

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

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.