JavaScript: manipulating objects with Object.keys()

A lightweight introduction into object looping and manipulation using Object.keys(), and various other native JavaScript methods.

Object.keys()

In a nutshell: Object.keys() extracts keys from a given object, the returned array can be used as is, or couple it with a forEach loop.

The Object.keys() method returns an array of a given object’s own enumerable properties… MDN

Here’s a simple example:

var nameObj = {first: "Zaphod", last: "Beeblebrox"};
console.log(Object.keys(nameObj));
// Outputs:
// ["first", "last"]

Object.keys() plus forEach() equals awesome

Now throw in Array.prototype.foEach(), and you’ve got a powerful loop structure at your disposal:

var nameObj = {first: "Zaphod", last: "Beeblebrox"};

Object.keys(nameObj).forEach(function(key) {
    console.log(key + ': ' + nameObj[key]);
});

// Outputs:
// first: Zaphod
// last: Beeblebrox

Array.prototype.some()

Array.prototype.some() method makes it easy to check if some values in the object pass the given test. Here’s an example using an Object of countries and their populations:

var countries = {
    China: 1371980000,
    India: 1276860000,
    'United States': 321786000,
    Indonesia: 255461700,
    Brazil: 204873000,
    Pakistan: 190860000
};

// Test function
function isRealyBig(element) {
    return countries[element] > 1000000000;
}

// Using the countries array the following condition should return true
if (Object.keys(countries).some(isRealyBig)) {
    console.log('Object contains a large country');
}

When some() hits a country that’s population is greater than 1000000000, it returns immediately. It’s enough if one of the values is over the given threshold.

Or maybe you want to break out of the loop? Do it with some():

Object.keys(countries).some(function(key) {
    // A condition to choose where to break
    return countries[key] < 1000000000;
});

Array.prototype.every()

Like the name says, every() tests every value in the array:

function isBigEnough(element) {
  return countries[element] > 1000000000;
}
if (Object.keys(countries).every(isBigEnough)) {
  console.log('Yup, all are over billion');
} else {
  console.log('Under a billion');
}

Array.prototype.filter()

The following filters out countries with population under a billion, and return their keys (country name):

var countries = {
    China: 1371980000,
    India: 1276860000,
    'United States': 321786000,
    Indonesia: 255461700,
    Brazil: 204873000,
    Pakistan: 190860000
};
countries = Object.keys(countries).filter(function(key) {
    // Countries under 1000000000
    return countries[key] <= 1000000000;
});
console.log(countries);
// Results in:
// ["UnitedStates", "Indonesia", "Brazil", "Pakistan"]

Array.prototype.map()

Want to return the value (population) instead of the key (country name)? Chain it with Array.prototype.map():

var countries = {
    China: 1371980000,
    India: 1276860000,
    'United States': 321786000,
    Indonesia: 255461700,
    Brazil: 204873000,
    Pakistan: 190860000
};
var countriesFiltered = Object.keys(countries).filter(function(key) {
    return countries[key] <= 1000000000;
}).map(function(key) {
    return countries[key];
});
console.log(countriesFiltered);
// Returns:
// [321786000, 255461700, 204873000, 190860000]

map() looks at every node in the array and replaces that node with something else you give it. Below is a simple example from the MDN docs that illustrates this clearly:

var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
    return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]

Conclusions

The basic idea with Object.keys() is not to loop the object, but ‘reduce’ it to an array, and then do stuff to the array.

Also a little demo:

JS Bin on jsbin.com

Comments

  • Bart Montana says:

    One of the most succinct and helpful posts I’ve run across while searching to learn the JS Object property. Chaining with examples of other methods is extremely helpful, so thank you for your post.

  • Karl says:

    Thanks for the clear examples … loving these native JS methods!

  • Cory says:

    Simple and concise!

Club-Mate, the beverage → club-mate.fi