AppDividend
Latest Code Tutorials

Javascript Object Keys Example | Object.keys() Tutorial

0

Javascript Object Keys Example | Object.keys() Tutorial is the topic, we will discuss today. The Javascript Object.keys() method returns an array of the given object’s property names, in the same order as we get with a standard loop. Object.keys() method 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.

If you want to learn more about the latest Javascript tutorials then check out this The Complete Javascript Course 2018.

Javascript Object Keys Example

Object.keys() is used for returning enumerable properties of a simple array. The Object.keys() is used for returning enumerable properties of an array-like object. The Object.keys() is used for returning enumerable properties of an array like object with a random key ordering.

The syntax for Object.keys() method is following.

Object.keys(obj)

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

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

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

 

Object.keys() Tutorial

Non-enumerable properties

The Object.keys() will only return the keys of enumerable properties. An example like a function property of an object is Non-enumerable property. We will not get the keys for 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));

 

Javascript Object Keys Example

Finally, Javascript Object Keys Example | Object.keys() Tutorial is over.

Leave A Reply

Your email address will not be published.

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