Latest Code Tutorials

JavaScript Object.keys: How to Get Keys of Object

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

Object.keys in JavaScript

The Object.keys() is a built-in JavaScript function 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 returns 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.




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

Return Value

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


To perform the Object.keys() example, you 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, you should install it.

Let us take a simple example.

// app.js

let obj = {
    name: 'Krunal',
    education: 'IT Engineer'
} ;

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 get 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 = [

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


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. Therefore, we will not get the keys to that property.

Let us take an example.

// app.js

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


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

See the following output.

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

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

Object.keys() and Array.forEach()

JavaScript does not have Object.forEach() method. So, to iterate through all the keys, use the 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 => {

See the following output.

Object.keys() and Array.forEach()

We can use the Object.values() function if we want the object’s values.

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) are in the order they were created.
  3. Finally, all symbols are in the order in which they were created.

If we want to sort the Javascript Object Keys(), we need to use the 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'

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


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


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


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);

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 applying dot notation or bracket notation consecutively.

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.


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


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


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 = [
        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 (, prop)) {

      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (, dontEnums[i])) {
      return result;

Browser 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.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”);
    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.