Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an object's properties in JavaScript / jQuery?

In JavaScript / jQuery, if I alert some object, I get either [object] or [object Object]

Is there any way to know:

  1. what is the difference between these two objects

  2. what type of Object is this

  3. what all properties does this object contains and values of each property

?

like image 856
Saiful Avatar asked Nov 02 '10 15:11

Saiful


People also ask

How do you check if an object has a property in JavaScript?

We can check if a property exists in the object by checking if property !== undefined . In this example, it would return true because the name property does exist in the developer object.

How can you get the list of all properties in an object in JavaScript?

To get all own properties of an object in JavaScript, you can use the Object. getOwnPropertyNames() method. This method returns an array containing all the names of the enumerable and non-enumerable own properties found directly on the object passed in as an argument.

What are object properties in JavaScript?

An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.

How is an object property referenced in JavaScript?

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.


1 Answers

You can look up an object's keys and values by either invoking JavaScript's native for in loop:

var obj = {     foo:    'bar',     base:   'ball' };  for(var key in obj) {     alert('key: ' + key + '\n' + 'value: ' + obj[key]); } 

or using jQuery's .each() method:

$.each(obj, function(key, element) {     alert('key: ' + key + '\n' + 'value: ' + element); }); 

With the exception of six primitive types, everything in ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toString method on an object, like this:

alert(Object.prototype.toString.call([])); 

The above will output [object Array].

There are several other class names, like [object Object], [object Function], [object Date], [object String], [object Number], [object Array], and [object Regex].

like image 131
jAndy Avatar answered Sep 28 '22 14:09

jAndy