Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Object.entries and Object.keys?

Tags:

What's the difference between Object.entries and Object.keys? In which case should I use one or the other one?

like image 842
Guerric P Avatar asked Mar 09 '19 14:03

Guerric P


People also ask

What does object keys mean?

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

What are the types of keys in objects?

Against what many think, JavaScript object keys cannot be Number, Boolean, Null, or Undefined type values. Object keys can only be strings, and even though a developer can use other data types to set an object key, JavaScript automatically converts keys to a string a value.


2 Answers

Object.keys returns only the own property names and works for ES5.

Object.entries returns an array of arrays with key and value and works from ES6.

If you need only keys or like to filter the keys, then take Object.keys, otherwise Object.entries.

like image 116
Nina Scholz Avatar answered Nov 03 '22 11:11

Nina Scholz


Object.keys(obj) – returns an array of keys.

Object.entries(obj) – returns an array of [key, value] pairs.

Consider the below example.

 let user = {  name: "John",  age: 30 }; 

Object.keys(user) = ["name", "age"]

Object.entries(user) = [ ["name","John"], ["age",30] ]

When you want a key, value pair, you would use Object.entries. When you just want the key, you would use Object.keys.

like image 25
Utsav Patel Avatar answered Nov 03 '22 11:11

Utsav Patel