How do I access properties of a javascript object if I don't know the names?
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
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']]