3

I have a problem that i didn't know how to solve it, i have test some information of how i should comparing or checking a variable if it was an array or an object

I have tried this

console.log({} == []); // return false
console.log({1:"haha"} == {}); // return false
console.log(["haha"] == {}); // retun false

The problem is, that i want to know if a variable is actualy an object cause typeof of both [] or {} return object.

console.log(isobject({1:"haha"})) // should return true;
console.log(isobject(["haha"])); // should return false;

Or

console.log(isobject({})) // should return true;
console.log(isobject([])); // should return false;

Is there any function to check variable like above? Thanks for any correction.

Irvan Hilmi
  • 336
  • 1
  • 2
  • 12

3 Answers3

7

This would help.

var a = [], b = {};

console.log(Object.prototype.toString.call(a).indexOf("Array")>-1);
console.log(Object.prototype.toString.call(b).indexOf("Object")>-1);

console.log(a.constructor.name == "Array");
console.log(b.constructor.name == "Object");

There are many other ways, but the above is backward compatible in all browsers.

Related questions must be referred:

Check if a value is array

Check if a value is object

Vignesh Raja
  • 6,851
  • 1
  • 28
  • 39
4

arr = [1,2,3]

Array.isArray(arr) // should output true

for object I would do obj = {a:1}

Object.keys(obj).length // should output 1

so you could do

Object.keys(obj).length >= 0 // should be true if obj is obj literal.

jack blank
  • 4,745
  • 7
  • 38
  • 66
1

var jsonData = {
  Name:"Jonh Doe",
  Dept: {
    code: "cse",
    title: "Computer science & tech"
  },
  Courses: [
    {
      code: "cse123",
      name: "something"
    },{
      code: "cse123",
      name: "something"
    }
  ]
}

for(var item in jsonData){
  if(typeof jsonData[item] === "object"){
    var x = "";
    if(Array.isArray(jsonData[item])) x = "Array";
    else x = "object";
    console.log(item + " is " + x);
  }else{
    console.log(item + " is " + typeof jsonData[item]);
  }  
}