This article was originally published on webinuse.com
We have already mentioned JavaScript Object Keys when we spoke about Object manipulation in JavaScript. In this article, we are going to cover Object.keys()
in-depth.
What is the Object?
According to MDN, the Object class represents one of JavaScript’s data types. It is used to store various keyed collections and more complex entities. Objects can be created using the Object() constructor or the object initializer / literal syntax.
The Object is one of the most complex JavaScript data types. It can hold any other data type. It can hold functions, also. Here is an example of some objects.
//The first way of creating Object in JavaScript
const obj = {
id: 1,
name: "John",
username: "Doe"
}
//The second way of creating Object in
//JavaScript using Object constructor.
function Obj(id, name, username) {
this.id;
this.name;
this.username;
}
const user = new Obj(1, 'John', 'Doe');
//The third way of creating object in JavaScript
//is by using ES6 object literalls
let id = 1;
let name = 'John';
let username = 'Doe';
const obj = {
id,
name,
username
}
What are JavaScript Object Keys?
Every JavaScript Object consists of keys and values. The key is the “name” by which we can call a value. Let’s make an example.
const obj = {
id: 1,
name: "John",
username: "Doe"
}
In our example, keys are id, name, username, and values are 1, “John” and “Doe”. But there is a difference between the Object key, which is “the name” and Object.keys()
method.
What is JavaScript Object.keys() method?
The Object.keys()
method returns an array of a given object’s own enumerable property names, iterated in the same order that a normal loop would, as per MDN.
This means that when we use Object.keys()
it will return an array of strings. Those strings will be the keys of the Object.
let obj = {
id: 1,
name: 'John',
username: 'Doe'
}
console.log(Object.keys(obj));
//Result:
//(3) ['id', 'name', 'username']
One small thing though is that if the keys are numbers than Object.keys()
will return those number in ascending order, regardless of their order as keys in Object.
let obj = {
1: "One",
102: "One hundred and two",
25: "Twenty five",
64: "Sixty four"
}
console.log(Object.keys(obj));
//Result:
//(4) ['1', '25', '64', '102']
If there is a mix of letters and numbers then JavaScript Object Keys will firstly return numbers in ascending order, then letters in the order they appeared.
let obj = {
5: "Five",
'c': "Letter c",
1: "One",
'a': "Letter a"
}
console.log(Object.keys(obj));
//Result:
//(4) ['1', '5', 'c', 'a']
If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like JavaScript Array length – the definitive guide.
Top comments (0)