Why Object.entries?
The Object.entries () method is used to rotate the array of [key,values] entered as parameters. The ordering of the properties is the same as that given by looping over the property values of the object manually.
Syntax:
Object.entries(obj)
- obj: Returns the [key, value] pairs with enumerable property.
- return: Object.assign () returns an array of [key, value] pairs of the enumerable property of the transmitted object.
Exceptions :
- It causes a TypeError if the argument passed is not an object .
- It causes a RangeError if the key passed in the argument is not in the range of the property[key, value] pair .
JavaScript Object.entries Examples
Example 1
In the code example below, we did the following:
- First, we created an object called “animals.”
- We entered certain values in the Animals object. (bear, cat, dog, rabbit)
- Then we created a variable called “animalsInfo”.
- We applied this variable “new Map”. And we applied the Object.entries method into it. In this way, we have reached the object of animals.
let animals = {
bear: "bear",
cat: "cat",
dog: "dog",
rabbit: "rabbit"
};
let animalsInfo = new Map(Object.entries(animals));
console.log(animalsInfo.has("cat"));
console.log(animalsInfo.size);
console.log(animalsInfo.get("dog"));
output:
true
4
dog
Example 2
We have created an object named myNumbers. We entered certain values into this object. And we called these values with Object.entries ().
let myNumbers = {
first: 1,
second: 2,
third: 3
}
console.log(Object.entries(myNumbers)[0]);
console.log(Object.entries(myNumbers)[1]);
console.log(Object.entries(myNumbers)[2]);
output:
[“first”, 1]
[“second”, 2]
[“third”, 3]
Example 3
let myObject = {
name: "rick",
surname: "quenn"
}
console.log(Object.entries(myObject));
console.log(Object.entries(myObject)[0]);
console.log(Object.entries(myObject)[1]);
output:
0: (2) [“name”, “rick”]
1: (2) [“surname”, “quenn”]
length: 2
[“name”, “rick”]
[“surname”, “quenn”]
Example 4
let myObject = Object.create({}, {
getname: {
value() {
return this.name;
}
}
});
myObject.name = "alex";
console.log(Object.entries(myObject))
output:
[Array(2)]
> 0: (2) [“name”, “alex”]
> length: 1
Polyfill
if (!Object.entries) {
Object.entries = function( obj ){
var ownProps = Object.keys( obj ),
i = ownProps.length,
resArray = new Array(i); // preallocate the Array
while (i--)
resArray[i] = [ownProps[i], obj[ownProps[i]]];
return resArray;
};
}
Resources:
- https://developer.mozilla.org
- https://www.geeksforgeeks.org
- https://alligator.io
- https://stackoverflow.com
Browser Support
| Chrome | 5 |
| Edge | yes |
| Firefox | 4 |
| Internet Explorer | 9 |
| Opera | 11.6 |
| Safari | 5 |
| Android webview | yes |
| Chrome for Android | yes |
| Edge mobile | yes |
| Firefox for Android | 4 |
| Opera Android | 11.5 |
Leave a comment