ES2024 introduced the Object.groupBy() method in JavaScript.
This method groups the elements of an object based on string values returned by a callback function.
Object.groupBy() does not modify the original object.
// Create an Array const fruits = [ {name:“apples”, quantity:300}, {name:“bananas”, quantity:500}, {name:“oranges”, quantity:200}, {name:“kiwi”, quantity:150} ]; // Callback function to Group Elements function myCallback({ quantity }) { return quantity > 200 ? “ok” : “low”; } // Group by Quantity const result = Object.groupBy(fruits, myCallback); |
Object.groupBy() is a feature introduced in ES2024.
It has been supported in new browsers since March 2024.
The difference between Object.groupBy() and Map.groupBy() is:
Object.groupBy() groups elements into a JavaScript object.
Map.groupBy() groups elements into a Map object.
The Object.keys() method returns an array containing the keys of an object.
// Create an Object const person = { firstName: “John”, lastName: “Doe”, age: 50, eyeColor: “blue” }; // Get the Keys const keys = Object.keys(person); |
The JavaScript for…in statement iterates over the properties of an object.
for (let variable in object) { // code to be executed } |
The code inside the for…in loop is executed once for each property.
It iterates through the properties of an object.
const person = { fname:” John”, lname:” Doe”, age: 25 }; for (let x in person) { txt += person[x]; } |