Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can loop through keys like this:</p> <pre><code>for (var key in data) { console.log(key); } </code></pre> <p>This logs "Name" and "Value".</p> <p>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 <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model" rel="noreferrer">prototype</a>:</p> <pre><code>for (var key in data) { if (data.hasOwnProperty(key)) { console.log(key); } } </code></pre> <p>As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:</p> <pre><code>for each (var value in data) { console.log(value); } </code></pre> <p>This example loops through values, so it would log <code>Property Name</code> and <code>0</code>. N.B.: The <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for_each...in" rel="noreferrer"><code>for each</code></a> syntax is mostly only supported in Firefox, but not in other browsers.</p> <p>If your target browsers support ES5, or your site includes <a href="https://github.com/es-shims/es5-shim" rel="noreferrer"><code>es5-shim.js</code></a> (recommended), you can also use <code>Object.keys</code>:</p> <pre><code>var data = { Name: 'Property Name', Value: '0' }; console.log(Object.keys(data)); // =&gt; ["Name", "Value"] </code></pre> <p>and loop with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" rel="noreferrer"><code>Array.prototype.forEach</code></a>:</p> <pre><code>Object.keys(data).forEach(function (key) { console.log(data[key]); }); // =&gt; Logs "Property Name", 0 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload