Object.keys ( ), values ( ), entries( )
Akhand Patel
Posted on May 30, 2021
As the title suggests in this post we will try to understand these static functions in the ** Object ** Class. These functions will likely save you a lot of time in future. Let's take a look at each of them.
We will use the following object in all the code examples further
let myObj = {email: "srockwell0@exblog.jp",
first_name: "Siusan",
gender: "Bigender",
id: 1,
ip_address: "86.247.200.113",
last_name: "Rockwell"}
Object.keys()
According to MDN,
*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. *
Let's break this down, this method takes an object as an argument and return an array consisting of all the property names(keys) of that object.
If we pass our myObj
as argument then we will get the following array
console.log(Object.keys(myObj));
// output: Array ["email", "first_name", "gender", "id", "ip_address", "last_name"]
Object.values()
According to MDN,
*The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. *
Let's break this down, this method takes an object as an argument and return an array consisting of all the values associated with the keys of that object.
If we pass our myObj
as argument then we will get the following array
console.log(Object.values(myObj));
// output: Array(6) ["srockwell0@exblog.jp", "Siusan", "Bigender", 1, "86.247.200.113", "Rockwell"]
Object.entries()
According to MDN,
*The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. *
This one looks scary, but fear not, help is here. This function same as others takes up an object but returns an array of arrays. The inner arrays at index 0 have the key and at index 1 the value associated with it.
console.log(Object.entries(myObj));
// output: (6) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]
0: (2) ["email", "srockwell0@exblog.jp"]
1: (2) ["first_name", "Siusan"]
2: (2) ["gender", "Bigender"]
3: (2) ["id", 1]
4: (2) ["ip_address", "86.247.200.113"]
5: (2) ["last_name", "Rockwell"]
I hope we were able to clear some doubts together.
Thank you for your time and see you in the next one.
Posted on May 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.