Iterate over Object Literal Values

Let's setup our basic object before we get started:

const x = {
  x: 1,
  y: 2,
  z: 3
};

We can use Object.keys(x) to return an array of all of the keys within our object.

Object.keys(x)
> ['x', 'y', 'z']

Now we able to map, filter, reduce and loop over our array and do something with that value within our object:

Object.keys(x).map(key => x[key] + 1)
> [2,3,4]

Object.keys(x).forEach(key => console.log(x[key]))
> [1,2,3]

The main take away here is that we have to use the key to access that specific value, it works but it feels a little clunky. ES2017 brings with it Object.values() which can be used as a nice shortcut for returning an array of all of the values within an Object.

Object.values(x)
> [1,2,3]

Object.values(x).map(value => value + 1)
> [2,3,4]

Object.values(x).forEach(value => console.log(value))
> [1,2,3]

You can read more about Object.values() at MDN, they also include a polyfill, should you need to support older browsers & browsers which haven't yet implemented it.

There's also Object.entries() which conveniently allows you to access the keys and the values. It returns an array containing arrays (first item being the key and the second item being the value.

Object.entries(x);
> [['x', 1], ['y', 2], ['z', 3]]

We can use de-structuring to easily get at these values:

Object.entries(x).map(([key, value]) => console.log(key, value))

var obj = {
    'foo': 1,
    'bar': 2
};

for (var key in obj) {
    console.log(obj[key]);
}

Or with jQuery:

$.each(obj, function(key, value) {
    console.log(this, value, obj[key]);
});

You should not have to depend on jQuery for this.

Object.keys(obj).forEach(function (key) {
  var value = obj[key];
   // do something with key or value
});
  • Mozilla Developer documentation - https://developer.mozilla.org

  • Polyfill for old browsers

  • View Performance Results - https://jsperf.com

Tags:

Javascript