JavaScript iterate through object keys and values
I just wanted to keep this for reference how to quickly loop through an objects keys and values, if needed. I also included an implementation using jQuery .each
Note the limitations of using a for...in loop, as it iterates over the properties of an object in an arbitrary order, and needs to use .hasOwnProperty, unless inherited properties want to be shown.
<b>Show objects</b>
function showObject(obj) {
var result = "";
for (var p in obj) {
if( obj.hasOwnProperty(p) ) {
result += p + " , " + obj[p] + "\n";
}
}
return result;
}
<b>Show objects with .each</b>
function showObjectjQuery(obj) {
var result = "";
$.each(obj, function(k, v) {
result += k + " , " + v + "\n";
});
return result;
}
<b>Test it out</b>
var test = {
'type' : 'news',
'name' : 'article1'
};
showObject(test);
// type , news name , article1
showObjectjQuery(test);
// type , news name , article1
<b>A more useful example calling a function on the object keys and values</b>
This approach of looping through keys and values in an object can be used to perform more useful operations on the object, for instance the method could call a function passed in on each of the values. An example of this is in the foIn method in mout.js which iterates through the object keys and values calling the function passed in.
function forIn(obj, fn, thisObj){
var key, i = 0;
for (key in obj) {
if (exec(fn, obj, key, thisObj) === false) {
break;
}
}
function exec(fn, obj, key, thisObj){
return fn.call(thisObj, obj[key], key, obj);
}
return forIn;
});
<b>Example use of forIn</b>
function Foo(){
this.foo = 1;
this.bar = 2;
}
var obj = new Foo();
var result = 0;
var keys = [];
forIn(obj, function(val, key, o){
result += val;
keys.push(key);
});
console.log(result); // 3
console.log(keys); // ['foo', 'bar']
Related protips:
Written by Steven Iseki
Related protips
9 Responses
Why aren’t you passing the corresponding object to JSON.stringify
?
The showObject method here is not really useful in itself, as we could use JSON.stringify() to acheive this result. I was just putting this in as a reference as to how to iterate through all keys and values in an object. I will rename the pro tip to that.
It could be useful to use this approach to create an array of all the keys in an object and pass that back, or we could pass in a function to a method like this which iterates through the keys and values, and calls the function for specific values.
There’s also Object.keys
in Node.js and modern browsers. See MDN for details.
And for compatibility with all browsers before using Object.keys() call this:
if (!Object.keys) Object.keys = function(o) {
if (o !== Object(o))
throw new TypeError('Object.keys called on a non-object');
var k = [],
p;
for (p in o)
if (Object.prototype.hasOwnProperty.call(o, p)) k.push(p);
return k;
}
I find this useful for me:
ObjectKit.forEach = function Object_forEach (object, callback) {
for (var key in object) {
if (object.hasOwnProperty(key)) callback(key, object[key]);
}
};
Looks Good
Sufficiently informative
When retrieving several key-value pairs from an object in JavaScript, you might need to cycle across the object. In this post, we'll examine four alternative JavaScript methods for looping through object attributes.
The for...in loop was the only method for iterating over an object prior to ES6. In ES6, the Object.keys() method was added to make iterating through objects simpler. Two new methods, Object.entries() and Object.values, were later introduced to ES8 (). The most recent methods arrayize the object before iterating across the array using array looping techniques.
Let's start with the first approach!
When retrieving several key-value pairs from an object in JavaScript, you might need to cycle across the object. In this post, we'll examine four alternative JavaScript methods for looping through object attributes.
The for...in loop was the only method for iterating over an object prior to ES6. In ES6, the Object.keys() method was added to make iterating through objects simpler. Two new methods, Object.entries() and Object.values, were later introduced to ES8 (). The most recent methods arrayize the object before iterating across the array using array looping techniques.
Let's start with the first approach!