Object Enumerable and non-enumerable properties
Every object has keys and values enclosed in parenthesis.
Object example
//inline object creation and initilization
const myobject = {
studentid:"1",
studentname:"Tom",
};
myobject.class="5th class"; // assignment syntax
The above example created an object with several properties - studentid, studentname, and class. An object has enumerable and non-enumerable properties of an object.
for(let key in myobject){
console.log(key +'-'+myobject[key])
}
Output is
studentid-1
studentname-Tom
class-5th class
As you have seen in the above example, During the iteration of an object, properties are printed to the console. These properties are called enumerable properties.
We have created objects with inline syntax and assigned data using assignment syntax.
We can add properties to an object using Object.defineProperty and called object non-enumerable properties. These are displayed during an iteration of an object.
enumerable:false
makes property non-enumerable.
Object.defineProperty(myobject,"address",{value:"India",enumerable:false})
ES8 introduced the following two new methods to the Object
class
- Object.entries()
- Object.values()
This post talks about the object.entries() method
and its examples.
object entries method
How do you iterate objects? So for-in loop is used to iterate each element of an object.
Object.entries() method returns an array of elements with each element in the format of [key, value] in the same order.
So what is special about the object.entries() method, as for-in loop also do the same thing.
entries method returns own enumerable properties, not the properties inherited from prototype inheritance. the for-in loop returns enumerable properties of an object and its parent via prototype inheritance.
Syntax
Object.entries(myobject)
Parameters and returns
- Input parameters - myobject is input provided to iterate the elements
- Return type - returns an array of object keys and values.
Let’s see an example to print keys and properties in an array
console.log(Object.entries(myobject))
Output is
[ [ 'studentid', '1' ],
[ 'studentname', 'Tom' ],
[ 'class', '5th class' ] ]
Support This method supports the latest browsers, old browsers need not have support for it.
Polyfill
is required to support old browsers.