Skip to content

Object.keys()

Why Object.keys ?

The Object.keys () method is a method for us to return the enumerable properties on an object to the array. The order of the properties is the same as given by the manual translation of the object’s properties.

Syntax:

Object.keys( obj )

obj:

  • The object to which the enumerable properties return their properties.
  • If we don’t pass any argument then it throws error
  • Returns an empty array if we discard an empty object.

Important parts:

  • Returns the TypeError error if the arguments passed to the Object.keys () method are not an object.
  • If an object is not passed as an argument to the method, then it convinces it and sees it as an object.
  • Object.keys () is used to return the enumerable properties of a simple directory.
  • Object.keys () is used to find or return arbitrary properties of an array-like object in random key order.

JavaScript Object.keys Examples

Example 1

  • We wrote an object named myObj. We entered certain values ​​into this (name, surname, age, from).
  • We then applied the Object.keys () method from outside the object. In this way, we have the following output.

        let myObj = {
            name: "alex",
            surname: "allen",
            from: "England",
            age: 32
        };

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

output:

[“name”, “surname”, “from”, “age”]


Example 2

Object.keys () returns the keys in the object as an array. Sometimes the Object.keys () method is applied to the array. If we do this, we get the following error message:

        let myArray = ["first", "second", "third"];

        let arr = Object.keys(myArray);

        consolelog(arr)

output:

Uncaught ReferenceError: consolelog is not defined
at HTMLPage1.html:20


Example 3

        let arr1 = Object.keys( "truecodes" );
        let arr2 = Object.keys( 1453 );
        let arr3 = Object.keys( 1, 2, 3.4 );
        let arr4 = Object.keys( true );
        let arr5 = Object.keys( [1, 2, 3], 4, 5 );


        console.log( arr1 )
        console.log( arr2 )
        console.log( arr3 )
        console.log( arr4 )
        console.log( arr5 )

output:

[“0”, “1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”]
[]
[]
[]
[“0”, “1”, “2”]


Example 4

        let myObject = {
            name: "alex",
            surname: "allen",
            fullname: function () {
                return this.name + this.surname;
            }
        };

        let myObjectKeys = Object.keys(myObject);

        console.log(myObjectKeys);

output:

[“name”, “surname”, “fullname”]


Polyfill

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

Sources:


Browser Support

Chrome5
Edgeyes
Firefox4
Internet Explorer9
Opera12
Safari5
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: