What's the difference between Object.entries
and Object.keys
? In which case should I use one or the other one?
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.
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.
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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With