-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;}
}
Maxxx
  • 3,688
  • 6
  • 28
  • 55
  • you can use `typeof` to check whether its string or not. – Prathamesh Koshti Nov 17 '20 at 06: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'); }` – Eric Stotch Nov 17 '20 at 06: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;}}``` – Ehtesham Ahmad Nadim Nov 17 '20 at 06:34

3 Answers3

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))
brk
  • 48,835
  • 10
  • 56
  • 78
  • I think using `for (let [key,value] of Object.entries(myObj))` will be better since he gets to have the property name. [example here](https://repl.it/join/ygtnhjwo-dochan) – doc-han Nov 17 '20 at 06:32
  • maybe also a `return false` after the for loop ;) ? – Nick Parsons Nov 17 '20 at 06:51
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'
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
0
if (typeof varible === 'object') {
    // is object
}

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

Torsten Barthel
  • 3,059
  • 1
  • 26
  • 22