Javascript Object Keys Tutorial with Object.Keys() Method

Article By Digamber Rawat on
JavaScript Object Keys tutorial with Object.Keys() method is going to be explored in this tutorial. Assume the scenario where you need to get the properties name from the object, and this is where JavaScript’s Object.keys() method comes in handy.

The Object.keys() method is a very helpful method offered by JavaScript. It returns an array of the given object’ property names with the same format as we get with a standard loop.

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon an object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

JavaScript Object keys syntax

Check out Object.keys() syntax below, It takes JavaScript Object and returns its name properties in the array form.

Object.keys(obj)

JavaScript Object.keyS() examples

let profile = {
  name: 'Rober Dw. Jr',
  age: 45,
  work: 'Actor'
};

console.log(Object.keys(profile));
// output: Array ["name", "age", "work"]

Let us get the array’s key as well with JavaScript Object keys method. I’ve defined the fruits array and getting the key value very easily with Object.keys() method.

let fruits = [
    'mango',
    'apple',
    'peach',
    'pineapple',
    'uava',
    'sugarcane'
];

console.log(Object.keys(fruits));
// output: ["0", "1", "2", "3", "4", "5"]

Getting random key ordering with Object.keys() method.

var myObj = { 
  200: 'a', 
  19: 'b', 
  89: 'c' 
};

console.log(Object.keys(myObj)); 
// output: ["19", "89", "200"]

Non-enumerable properties

The Object.keys() works only with enumerable properties. It doesn’t co-operate well with Non-numerable properties. Let us check out below.

// getHello is a property which isn't enumerable
let newObj = Object.create({}, {
  getHello: {
    value: function () { return this.foo; }
  } 
});

newObj.world = 1;

console.log(Object.keys(newObj)); 
// output: ['world']

Javascript Object Keys tutorial is over for now.

Digamber Rawat

Feel free to contact me, If you are looking for a freelance full stack Developer, with the following skills: Mongo DB, Express JS, Angualr 2+, Node JS, Loopback JS, Firebase, Ionic Framework and WordPress. I also offer remote contracting service to the clients across the globe. Hire Me