-1

So right now, I created an example of a JSON object where:

var myObj = {
    address: {
        0: ["41 Lake Avenue"]
    },
    name: "jake"
}

myObj itself as a whole is a JSON object, and inside it, I have two keys which are address and name respectively. So the value of the address key is also an Object since its in braces, where as the name key value is just a string.

I want to write a simple check in javascript to check whether or not the keys in myObj is an object or a string. So if its an object, it returns true where as if its not an object it returns false. Therefore for address, it would be true while for name, it would be false.

I tried looking around for some isObject() method similar to isArray() but apparently i couldn't find so I'd like some help on this so i wrote a pseudocode below for the logic:

for (i=0;i<2;i++) {
   if myObj[i] is Object {
      return true;}
   else{
      return false;}
}
3
  • you can use typeof to check whether its string or not. Commented Nov 17, 2020 at 6:25
  • I'm new here and rarely program in JS but wtf are these comments and answers. You did the entire thing wrong. Use for in for (k in myObj) { console.log(typeof(myObj[k]) == 'string'); } Commented Nov 17, 2020 at 6:33
  • The typeof operator returns a string indicating the type of the unevaluated operand: for (let [key, value] of Object.entries(myObj)) { if( value && typeof value =='object'){return true;} else{ return false;}} Commented Nov 17, 2020 at 6:34

3 Answers 3

2

You can use typeof.

Note: The question is not clear and does not explains what will happen if there multiple keys with value as an object. Since the below function will return as soon as it comes across a key whose value is a object

var myObj = {
  address: {
    0: ["41 Lake Avenue"]
  },
  name: "jake"
}


function isObject(obj) {
  for (let keys in obj) {
    if (typeof obj[keys] === 'object' && obj[keys] !== null) {
      return true
    }
  }
}

console.log(isObject(myObj))

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

2 Comments

I think using for (let [key,value] of Object.entries(myObj)) will be better since he gets to have the property name. example here
maybe also a return false after the for loop ;) ?
0
if (typeof varible === 'object') {
    // is object
}

But Null is also recognized as object. So you could also proove that.

Comments

0

You need to use the typeof(var) operator : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

For object:

typeof yourVariable === 'object' && yourVariable !== null

For string:

typeof yourVariable === 'string'

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.