_kakfa
Last Updated: February 07, 2017
·
177.6K
· steveniseki
Stevenm

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

5 Responses
Add your response

14977
2848a8fa5d13b7b208c636da5f48b141

Why aren’t you passing the corresponding object to JSON.stringify?

over 1 year ago ·
14989
Stevenm

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.

over 1 year ago ·
14991
2848a8fa5d13b7b208c636da5f48b141

There’s also Object.keys in Node.js and modern browsers. See MDN for details.

over 1 year ago ·
17373
Kreso 300x300

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;
}
over 1 year ago ·
27038
000f45b685d4d6ff1a171676512c382e

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]);
  }
};
over 1 year ago ·