Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that value is object literal?

Tags:

javascript

I have a value and want to know if it's an iteratable object literal, before I iterate it.

How do I do that?

like image 543
ajsie Avatar asked Dec 01 '10 02:12

ajsie


People also ask

How do you know if an object is literal?

There is no way to tell the difference between an object built from an object literal, and one built from other means. It's a bit like asking if you can determine whether a numeric variable was constructed by assigning the value '2' or '3-1';

How do you check if all object values are true?

To check if all values in object are equal to true :Use the Object. values() method to get an array of the object's values. Call the every() method on the array. The every method will test if all values in the array are equal to true and will return the result.

How do you check it is object or not in JavaScript?

Method 1: Using the typeof operator The typeof operator returns the type of the variable on which it is called as a string. The return string for any object that does not exist is “undefined”. This can be used to check if an object exists or not, as a non-existing object will always return “undefined”.


2 Answers

This should do it for you:

if( Object.prototype.toString.call( someObject ) === '[object Object]' ) {     // do your iteration } 

From ECMAScript 5 Section 8.6.2 if you're interested:

The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String". The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).

like image 135
user113716 Avatar answered Oct 04 '22 15:10

user113716


You could also do something like:

    if (someObject.constructor == Object) {         // do your thing     } 

you can read more about it here

like image 34
dcestari Avatar answered Oct 04 '22 15:10

dcestari