128

Say you have a javascript object like this:

var data = { foo: 'bar', baz: 'quux' };

You can access the properties by the property name:

var foo = data.foo;
var baz = data["baz"];

But is it possible to get these values if you don't know the name of the properties? Does the unordered nature of these properties make it impossible to tell them apart?

In my case I'm thinking specifically of a situation where a function needs to accept a series of name-value pairs, but the names of the properties may change.

My thoughts on how to do this so far is to pass the names of the properties to the function along with the data, but this feels like a hack. I would prefer to do this with introspection if possible.

Adam Lassek
  • 35,156
  • 14
  • 91
  • 107

8 Answers8

146

You can loop through keys like this:

for (var key in data) {
  console.log(key);
}

This logs "Name" and "Value".

If you have a more complex object type (not just a plain hash-like object, as in the original question), you'll want to only loop through keys that belong to the object itself, as opposed to keys on the object's prototype:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    console.log(key);
  }
}

As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:

for each (var value in data) {
  console.log(value);
}

This example loops through values, so it would log Property Name and 0. N.B.: The for each syntax is mostly only supported in Firefox, but not in other browsers.

If your target browsers support ES5, or your site includes es5-shim.js (recommended), you can also use Object.keys:

var data = { Name: 'Property Name', Value: '0' };
console.log(Object.keys(data)); // => ["Name", "Value"]

and loop with Array.prototype.forEach:

Object.keys(data).forEach(function (key) {
  console.log(data[key]);
});
// => Logs "Property Name", 0
Ron DeVera
  • 14,394
  • 6
  • 41
  • 36
  • Did you just make that last one up and actually got away with it? Well done... =) – nickl- Sep 25 '12 at 15:03
  • This exists in Firefox ([docs](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for_each...in)), but fair point that it's not universal. I'll update the answer to mention this. – Ron DeVera Sep 26 '12 at 00:12
  • 28
    btw alert is a bad way to debug things, try console.log – StackOverflowed Oct 21 '12 at 13:32
  • This was the best answer when the question was asked, but I'm removing the checkmark because later JS versions have provided better tools. – Adam Lassek Apr 25 '17 at 22:19
68

Old versions of JavaScript (< ES5) require using a for..in loop:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    // do something with key
  }
}

ES5 introduces Object.keys and Array#forEach which makes this a little easier:

var data = { foo: 'bar', baz: 'quux' };

Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
  // do something with data[key]
});

ES2017 introduces Object.values and Object.entries.

Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]
Adam Lassek
  • 35,156
  • 14
  • 91
  • 107
  • 2
    Now this actually answers the question, well done @Adam Lassek, very nicely done. – nickl- Sep 25 '12 at 15:05
  • It's misleading to use both 'name' and 'value' as object keys. This function only returns the keys in a list, not the values. { name1: 'value1', name2: 'value2' } will avoid confusion for beginners. Object.keys(data); // ['name1', 'name2'] – nicholsonjf Mar 15 '17 at 02:48
  • 3
    @JamesNicholson I agree, edited to be less confusing. – Adam Lassek Apr 25 '17 at 22:17
10
for(var property in data) {
    alert(property);
}
karim79
  • 339,989
  • 67
  • 413
  • 406
4

You often will want to examine the particular properties of an instance of an object, without all of it's shared prototype methods and properties:

 Obj.prototype.toString= function(){
        var A= [];
        for(var p in this){
            if(this.hasOwnProperty(p)){
                A[A.length]= p+'='+this[p];
            }
        }

    return A.join(', ');
}
Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
kennebec
  • 102,654
  • 32
  • 106
  • 127
3
function getDetailedObject(inputObject) {
    var detailedObject = {}, properties;

    do {
        properties = Object.getOwnPropertyNames( inputObject );
        for (var o in properties) {
            detailedObject[properties[o]] = inputObject[properties[o]];
        }
    } while ( inputObject = Object.getPrototypeOf( inputObject ) );

    return detailedObject;
}

This will get all properties and their values (inherited or own, enumerable or not) in a new object. original object is untouched. Now new object can be traversed using

var obj = { 'b': '4' }; //example object
var detailedObject = getDetailedObject(obj);
for(var o in detailedObject) {
    console.log('key: ' + o + '   value: ' + detailedObject[o]);
}
Adam Lassek
  • 35,156
  • 14
  • 91
  • 107
Shishir Arora
  • 5,521
  • 4
  • 30
  • 35
1

You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."

You can use any object in place of stats:

var stats = {
  a: 3,
  b: 6,
  d: 7,
  erijgolekngo: 35
}
/*  this is the answer here  */
for (var key in Object.keys(stats)) {
  var t = Object.keys(stats)[key];
  console.log(t + " value =: " + stats[t]);
}
Cloid J. Green
  • 119
  • 1
  • 7
1
var obj = {
 a: [1, 3, 4],
 b: 2,
 c: ['hi', 'there']
 }
for(let r in obj){  //for in loop iterates all properties in an object
 console.log(r) ;  //print all properties in sequence
 console.log(obj[r]);//print all properties values
}
Mayank_VK
  • 19
  • 1
  • 5
  • where this answer provides what is required by the OP but a little description of what you are doing and why the OP should use it would be nice, also don't forget `.hasOwnProperty()` when using for in to iterate an object. – Muhammad Omer Aslam Jan 23 '19 at 21:48
  • Thanks, I agree that .hasOwnProperty() iterates the object but it iterates to check a condition however using it we can't print all the properties of an object. Correct me if am wrong. – Mayank_VK Jan 24 '19 at 08:10
  • The `hasOwnProperty()` method returns a `boolean` indicating whether the object has the specified property **as its own property (as opposed to inheriting it)**. see this [example](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty#Iterating_over_the_properties_of_an_object) – Muhammad Omer Aslam Jan 24 '19 at 08:16
-2
var attr, object_information='';

for(attr in object){

      //Get names and values of propertys with style (name : value)
      object_information += attr + ' : ' + object[attr] + '\n'; 

   }


alert(object_information); //Show all Object
isaax2
  • 21
  • 2
  • This adds nothing to the accepted answer, and presents the information in the least useful way possible. And it doesn't account for inherited properties. – Adam Lassek Apr 16 '13 at 18:31