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

JavascriptJquery

Javascript Problem Overview


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

?

Javascript Solutions


Solution 1 - Javascript

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].

Solution 2 - Javascript

###To get listing of object properties/values:

  1. In Firefox - Firebug:

     console.dir(<object>);
    
  2. Standard JS to get object keys borrowed from Slashnick:

        var fGetKeys = function(obj){
           var keys = [];
           for(var key in obj){
              keys.push(key);
           }
           return keys;
        }
    
     // Example to call it:
    
        var arrKeys = fGetKeys(document);
    
        for (var i=0, n=arrKeys.length; i<n; i++){
           console.log(i+1 + " - " + arrKeys[i] + document[arrKeys[i]] + "\n");
        }
        
    

###Edits:

  1. <object> in the above is to be replaced with the variable reference to the object.
  2. console.log() is to be used in the console, if you're unsure what that is, you can replace it with an alert()

Solution 3 - Javascript

>i) what is the difference between these two objects

The simple answer is that [object] indicates a host object that has no internal class. A host object is an object that is not part of the ECMAScript implementation you're working with, but is provided by the host as an extension. The DOM is a common example of host objects, although in most newer implementations DOM objects inherit from the native Object and have internal class names (such as HTMLElement, Window, etc). IE's proprietary ActiveXObject is another example of a host object.

[object] is most commonly seen when alerting DOM objects in Internet Explorer 7 and lower, since they are host objects that have no internal class name.

> ii) what type of Object is this

You can get the "type" (internal class) of object using Object.prototype.toString. The specification requires that it always returns a string in the format [object [[Class]]], where [[Class]] is the internal class name such as Object, Array, Date, RegExp, etc. You can apply this method to any object (including host objects), using

Object.prototype.toString.apply(obj);

Many isArray implementations use this technique to discover whether an object is actually an array (although it's not as robust in IE as it is in other browsers).


> iii) what all properties does this object contains and values of each property

In ECMAScript 3, you can iterate over enumerable properties using a for...in loop. Note that most built-in properties are non-enumerable. The same is true of some host objects. In ECMAScript 5, you can get an array containing the names of all non-inherited properties using Object.getOwnPropertyNames(obj). This array will contain non-enumerable and enumerable property names.

Solution 4 - Javascript

I hope this doesn't count as spam. I humbly ended up writing a function after endless debug sessions: http://github.com/halilim/Javascript-Simple-Object-Inspect

function simpleObjInspect(oObj, key, tabLvl)
{
	key = key || "";
	tabLvl = tabLvl || 1;
	var tabs = "";
	for(var i = 1; i < tabLvl; i++){
		tabs += "\t";
	}
	var keyTypeStr = " (" + typeof key + ")";
	if (tabLvl == 1) {
		keyTypeStr = "(self)";
	}
	var s = tabs + key + keyTypeStr + " : ";
	if (typeof oObj == "object" && oObj !== null) {
		s += typeof oObj + "\n";
		for (var k in oObj) {
			if (oObj.hasOwnProperty(k)) {
				s += simpleObjInspect(oObj[k], k, tabLvl + 1);
			}
		}
	} else {
		s += "" + oObj + " (" + typeof oObj + ") \n";
	}
	return s;
}

Usage

alert(simpleObjInspect(anyObject));

or

console.log(simpleObjInspect(anyObject));

Solution 5 - Javascript

Get FireBug for Mozilla Firefox.

use console.log(obj);

Solution 6 - Javascript

Spotlight.js is a great library for iterating over the window object and other host objects looking for certain things.

// find all "length" properties
spotlight.byName('length');

// or find all "map" properties on jQuery
spotlight.byName('map', { 'object': jQuery, 'path': '$' });

// or all properties with `RegExp` values
spotlight.byKind('RegExp');

// or all properties containing "oo" in their name
spotlight.custom(function(value, key) { return key.indexOf('oo') > -1; });

You'll like it for this.

Solution 7 - Javascript

Scanning object for first intance of a determinated prop:

var obj = {a:'Saludos',
            b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
           d:'Hasta luego'
            }
function scan (element,list){
    var res;
    if (typeof(list) != 'undefined'){
        if (typeof(list) == 'object'){
            for(key in list){
               if (typeof(res) == 'undefined'){
                res = (key == element)?list[key]:scan(element,list[key]);
               }
            });
        }
    }
    return res;
}
console.log(scan('a',obj));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaifulView Question on Stackoverflow
Solution 1 - JavascriptjAndyView Answer on Stackoverflow
Solution 2 - Javascriptvol7ronView Answer on Stackoverflow
Solution 3 - JavascriptAndy EView Answer on Stackoverflow
Solution 4 - JavascriptHalil ÖzgürView Answer on Stackoverflow
Solution 5 - JavascriptZ. ZlatevView Answer on Stackoverflow
Solution 6 - JavascriptPaul IrishView Answer on Stackoverflow
Solution 7 - JavascriptJ Jesus Loera VView Answer on Stackoverflow