AppDividend
Latest Code Tutorials

Object.keys() Function in JavaScript: The Complete Guide

The objects in Javascript are containers for named values called properties or methods. The object contains keys and values. To access the keys of the object, use the keys() method. The keys() method in JavaScript is used for returning the enumerable properties of a simple array

Object.keys in JavaScript

The Object.keys() is a built-in JavaScript method that returns an array of the given object’s property names in the same order as we get with a standard loop. The Object.keys() method takes an object as an argument and returns the array of strings representing all the enumerable properties of a given object.

The Object keys() function is used to return the array whose elements are strings corresponding to the enumerable properties found directly upon the object.

An ordering of the properties is the same as that given by an object manually in the loop is applied to the properties.

Syntax

Object.keys(obj)

Arguments

The obj parameter is required, and its properties are to be returned.

Return Value

The return value is an array of strings that represent all the enumerable properties of a given object.

Example

To perform the Object.keys() example, you definitely installed Node.js in your machine. If you have not installed then install Node.js and NPM. It is not compulsory since you can use the online editor or browser. But if you want to run it locally, then you should install it.

Let us take a simple example.

// app.js

let obj = {
    name: 'Krunal',
    education: 'IT Engineer'
} ;
console.log(Object.keys(obj));

Save the file and run the file by typing the node app in the terminal.

Javascript Object Keys Example | Object.keys() Tutorial

So, in the above example, we are getting an array of object keys. We can do the same with an array. We can get the array keys as well.

// app.js

let objArr = [
    'apple',
    'microsoft',
    'amazon',
    'alphabet',
    'tencent',
    'alibaba'
];
console.log(Object.keys(objArr));

So, here we have defined an array. We will get the keys to each element in the returned array.

Tutorial

Non-enumerable properties

The Object.keys() will only return the keys of enumerable properties.

An example of a function property of an object is the Non-enumerable property. We will not get the keys to that property.

Let us take an example.

// app.js

let myObj = Object.create({}, {
    getName: {
        value: function () { return this.name; }
    }
});
myObj.name = 'krunal';

console.log(Object.keys(myObj));

Non-enumerable properties

How to get a length of Object

To get the length of an object in Javascript, use the length property. Everything in JavaScript is an Object.

You can define the string object, the array object, or use an Object constructor in JavaScript to create the object and add properties and values. Sometimes, you would also require knowing the length of an Object. 

// app.js

let unorderedData = {
  real_name: 'Millie Bobby Brown',
  character_name: 'Eleven',
  series: 'Stranger Things'
};
console.log(Object.keys(unorderedData).length)

See the following output.

➜ es git:(master) ✗ node app
3
➜ es git:(master) ✗

So, this is how to calculate or count how many properties have a JavaScript object.

Object.keys() and Array.forEach()

In JavaScript, there is no method such as Objects.forEach(). So, if we want to iterate through all the keys, then we can use Array.forEach() function.

See the following example.

// app.js

let data = {
  real_name: 'Millie Bobby Brown',
  character_name: 'Eleven',
  series: 'Stranger Things'
};
Object.keys(data).forEach(item => {
  console.log(item);
});

See the following output.

Object.keys() and Array.forEach()

If we want the object’s values, we can use the Object.values() function.

Sorting Object by keys

All methods that iterate over property keys do so in the same order:

  1. First of all, The array indices are sorted numerically.
  2. Then all string keys (that are not indices) in the order in which they were created.
  3. All symbols in the order in which they were created.

If we want to sort the Javascript Object Keys(), we need to use the following ES6 higher-order function.

  1. Array.forEach()
  2. Array.Sort()

See the following example.

// app.js

let unorderedData = {
  real_name: 'Millie Bobby Brown',
  character_name: 'Eleven',
  series: 'Stranger Things'
};
console.log(JSON.stringify(unorderedData));

const orderedData = {};
Object.keys(unorderedData).sort().forEach(function(key) {
  orderedData[key] = unorderedData[key];
});

console.log(JSON.stringify(orderedData));

See the following output.

➜ es git:(master) ✗ node app
{"real_name":"Millie Bobby Brown","character_name":"Eleven","series":"Stranger Things"}
{"character_name":"Eleven","real_name":"Millie Bobby Brown","series":"Stranger Things"}
➜ es git:(master) ✗

You can see that our Object keys() are now sorted according to the alphabet.

Object keys map in JavaScript

This is how you can rename your object keys using the Array.map() method.

// app.js

let obj = { 11: 'eleven', 21: 'mike', 10: 'will' };

Object.keys(obj).map(function (old_key, index) {
  let new_key = old_key * 11;
  if (old_key !== new_key) {
    Object.defineProperty(obj, new_key,
      Object.getOwnPropertyDescriptor(obj, old_key));
    delete obj[old_key];
  }
});

console.log(obj);

See the output.

➜  es git:(master) ✗ node app
{ '110': 'will', '121': 'eleven', '231': 'mike' }
➜  es git:(master) ✗

The above code will modify the object.

If you want to create a new object and do not modify the old object, write the following code.

// app.js

let obj = { 11: 'eleven', 21: 'mike', 10: 'will' };
const newObject = {};
Object.keys(obj).map(function (old_key, index) {
  let new_key = old_key * 11;
  delete Object.assign(newObject, { [new_key]: obj[old_key] })[old_key];
});

console.log(newObject);

See the output.

➜  es git:(master) ✗ node app
{ '110': 'will', '121': 'eleven', '231': 'mike' }
➜  es git:(master) ✗

So, we have changed the keys of the object. We have also used the delete operator and Object.assign() method.

So, this is how you can change javascript object keys.

A non-optimized way would be,

// app.js

o[ new_key ] = o[ old_key ];
delete o[ old_key ];

You could wrap the work in a function and assign it to the Object prototype. Maybe use the fluent interface style to make multiple renames flow.

Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName === newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};

Javascript Object keys to array

We can get the array of keys using the Object.keys() method.

// app.js

let obj = {
  'alpha': 'Google',
  'instagram': 'Facebook'
};

let keys = Object.keys(obj);
console.log(keys);

See the output.

➜  es git:(master) ✗ node app
[ 'alpha', 'instagram' ]
➜  es git:(master) ✗

You can use the $.map for the jquery library.

Accessing nested data structures in Javascript

The nested data structure is the array or an object which refers to other arrays or objects; for example, its values are arrays or objects.

Such data structures can be accessed by consecutively applying dot notation or bracket notation.

Here is an example:

// app.js

const info = {
  code: 11,
  items: [{
    id: 1,
    name: 'Eleven'
  }, {
    id: 2,
    name: 'Krunal'
  }]
};

Let’s assume that we want to access the name of the second item.

Here is how we can do it.

As we can see, the info is an object; hence we can access its properties using dot notation. The items’ property is accessed as follows.

info.items

The value is an array. To access the second element of an array, we have to use bracket notation:

info.items[1]

This value is the object, and we use the dot notation again to access the name property.

const info_name = info.items[1].name;

Alternatively, we could have used the bracket notation for any properties, mainly if the name contained characters that would have made it invalid for dot notation usage.

const item_name = info['items'][1]['name'];

Polyfill

If we want to add compatible Object.keys() support in older environments that do not support it, copy the following snippet.

if (!Object.keys) {
  Object.keys = (function() {
    'use strict';
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

    return function(obj) {
      if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) {
        throw new TypeError('Object.keys called on non-object');
      }

      var result = [], prop, i;

      for (prop in obj) {
        if (hasOwnProperty.call(obj, prop)) {
          result.push(prop);
        }
      }

      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) {
            result.push(dontEnums[i]);
          }
        }
      }
      return result;
    };
  }());
}

Browser Support

FEATURE BASIC SUPPORT
Chrome 45
Edge Yes
Firefox 25
Internet Explorer No
Opera 32
Safari 8
Android WebView Yes
Chrome for Android Yes
Edge mobile Yes
Firefox for Android 4
Opera Android Yes
iOS Safari 8

That is it for this tutorial.

Recommended Posts

Javascript Object.toString()

Javascript Object.is()

Javascript Object.defineProperty()

Javascript Object.freeze()

Javascript Object.values()

Javascript Object.assign()

Javascript Object.create()

1 Comment
  1. me says

    whenSetup(function () {
    });

    atTimestamp(1, “seconds”, function () {
    setVisibleEach(“ALIEN”, false);
    setVisibleEach(“ALIEN”, true);
    setBackgroundEffectWithPalette(“rand”, “cool”);
    setForegroundEffectExtended(“paint_drip”);
    makeNewDanceSpriteGroup(20, “ALIEN”, “circle”);
    makeNewDanceSpriteGroup(20, “ALIEN”, “border”);
    makeNewDanceSpriteGroup(20, “ALIEN”, “inner”);
    makeNewDanceSpriteGroup(20, “ALIEN”, “diamond”);
    makeAnonymousDanceSprite(“ROBOT”, {x: 200, y: 200});
    makeNewDanceSpriteGroup(20, “ALIEN”, “circle”);
    makeNewDanceSpriteGroup(20, “ALIEN”, “x”);
    makeNewDanceSpriteGroup(20, “ALIEN”, “column”);
    makeNewDanceSpriteGroup(20, “ALIEN”, “left”);
    makeNewDanceSpriteGroup(20, “ALIEN”, “bottom”);
    startMappingEach(sprites, “scale”, “bass”);
    setPropEach(“ROBOT”, “height”, 9999);
    setPropEach(“ROBOT”, “width”, 200);
    setPropEach(“ALIEN”, “height”, 250);
    setDanceSpeedEach(sprites, 4);
    setTintEachInline(sprites, ‘#ff0000’);
    });

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.