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.
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.
4 Answers
Reset to default 10This 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
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.
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]);
}
}
JSON.stringify(variable).startsWith("[")
This will return true when variable is an array.
JSON.stringify(variable).startsWith("{")
This will return true when variable is an object.
array instanceof Array
? – Irvan Hilmi Commented Nov 10, 2018 at 4:15