ποΈ Object Static Methods: Your Magical Toolbox
Imagine you have a treasure chest (your object). These static methods are like special tools that help you peek inside, copy treasures, lock the chest, and organize everything perfectly!
π― The Big Picture
JavaScript objects are like labeled boxes holding your stuff. Object static methods are helper tools that work on ANY boxβtheyβre attached to the Object itself, not individual boxes.
Think of it like this: You have a Master Keyring called Object. Each key on this ring does something special to ANY treasure chest you point it at!
π Object.keys() and Object.values()
The Story
Imagine a toy box with labeled compartments. Object.keys() reads all the labels. Object.values() grabs all the toys inside!
Object.keys() β Get All Labels
const pet = {
name: "Buddy",
type: "dog",
age: 3
};
const labels = Object.keys(pet);
// labels = ["name", "type", "age"]
What happened? We got an array of all the property names (keys)!
Object.values() β Get All Contents
const pet = {
name: "Buddy",
type: "dog",
age: 3
};
const contents = Object.values(pet);
// contents = ["Buddy", "dog", 3]
What happened? We got an array of all the values inside!
π Real-Life Use
Want to count how many properties? Use Object.keys(pet).length β gives 3!
π Object.entries() and Object.fromEntries()
The Story
Object.entries() is like unpacking a gift box into a list of tags + items. Object.fromEntries() is like repacking that list back into a gift box!
Object.entries() β Unpack Into Pairs
const fruit = {
apple: 5,
banana: 3
};
const pairs = Object.entries(fruit);
// pairs = [["apple", 5], ["banana", 3]]
Each pair is an array: [key, value]. Super useful for looping!
Object.fromEntries() β Pack Pairs Back
const pairs = [
["apple", 5],
["banana", 3]
];
const fruit = Object.fromEntries(pairs);
// fruit = { apple: 5, banana: 3 }
Magic! We turned an array of pairs back into an object!
π Real-Life Use
Transform data easily:
const prices = { apple: 1, banana: 2 };
const doubled = Object.fromEntries(
Object.entries(prices).map(
([key, val]) => [key, val * 2]
)
);
// doubled = { apple: 2, banana: 4 }
π¦ Object.assign() β Copy & Merge
The Story
Imagine copying stickers from one notebook to another. Object.assign() copies properties from source objects to a target object!
Basic Copy
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original);
// copy = { a: 1, b: 2 }
The {} is the empty target. We copied everything into it!
Merge Multiple Objects
const base = { a: 1 };
const extra = { b: 2 };
const more = { c: 3 };
const merged = Object.assign({}, base, extra, more);
// merged = { a: 1, b: 2, c: 3 }
β οΈ Watch Out!
Later sources overwrite earlier ones:
const first = { name: "Alice" };
const second = { name: "Bob" };
const result = Object.assign({}, first, second);
// result = { name: "Bob" } β Bob wins!
ποΈ Object.create() β Build From Blueprint
The Story
Instead of copying, Object.create() builds a NEW object that βinheritsβ from another objectβlike a child learning from a parent!
Basic Usage
const animal = {
speak() {
return "Some sound";
}
};
const dog = Object.create(animal);
dog.bark = function() {
return "Woof!";
};
dog.speak(); // "Some sound" β inherited!
dog.bark(); // "Woof!"
The dog can use speak() even though we never defined it on dogβit comes from animal!
π Why Use It?
Perfect for creating object hierarchies without classes. The new object βlooks upβ to its parent for missing properties.
π Object.freeze() and Object.seal()
The Story
Sometimes you want to protect your treasure chest!
- Object.freeze() = Locks it completely. Nothing can change!
- Object.seal() = You canβt add/remove items, but you CAN modify existing ones.
Object.freeze() β Total Lockdown
const config = { theme: "dark" };
Object.freeze(config);
config.theme = "light"; // β Ignored!
config.newProp = "hi"; // β Ignored!
// config is still { theme: "dark" }
Object.seal() β Partial Protection
const settings = { volume: 50 };
Object.seal(settings);
settings.volume = 80; // β
Works!
settings.newProp = "x"; // β Ignored!
delete settings.volume; // β Ignored!
// settings = { volume: 80 }
Quick Comparison
| Action | freeze() | seal() |
|---|---|---|
| Change existing value | β No | β Yes |
| Add new property | β No | β No |
| Delete property | β No | β No |
β Object.hasOwn() β Check Ownership
The Story
Sometimes you need to ask: βDoes this object directly own this property?β
Why Not Just Use in?
The in operator checks inherited properties too. Object.hasOwn() only checks the object itself!
const car = { brand: "Toyota" };
Object.hasOwn(car, "brand"); // true
Object.hasOwn(car, "toString"); // false
// But with 'in':
"brand" in car; // true
"toString" in car; // true β inherited!
Modern & Safe
Object.hasOwn() is the modern, recommended way. Itβs safer than the old hasOwnProperty method!
const data = { name: "Test" };
// Modern way β
Object.hasOwn(data, "name");
// Old way (still works)
data.hasOwnProperty("name");
ποΈ Object.groupBy() β Sort Into Categories
The Story
Imagine sorting your toys into different bins by color. Object.groupBy() does exactly that for arrays!
Basic Example
const fruits = [
{ name: "apple", color: "red" },
{ name: "banana", color: "yellow" },
{ name: "cherry", color: "red" }
];
const grouped = Object.groupBy(
fruits,
fruit => fruit.color
);
// grouped = {
// red: [
// { name: "apple", color: "red" },
// { name: "cherry", color: "red" }
// ],
// yellow: [
// { name: "banana", color: "yellow" }
// ]
// }
How It Works
- You give it an array
- You give it a function that returns a βgroup keyβ
- It sorts items by that key!
π Real-Life Use
Grouping users by role, products by category, or data by date!
const users = [
{ name: "Alice", role: "admin" },
{ name: "Bob", role: "user" },
{ name: "Carol", role: "admin" }
];
const byRole = Object.groupBy(
users,
user => user.role
);
// Now admins and users are separated!
π― Quick Summary
graph TD A["Object Static Methods"] --> B["keys/values"] A --> C["entries/fromEntries"] A --> D["assign"] A --> E["create"] A --> F["freeze/seal"] A --> G["hasOwn"] A --> H["groupBy"] B --> B1["Get labels or contents"] C --> C1["Convert to/from pairs"] D --> D1["Copy & merge objects"] E --> E1["Inherit from blueprint"] F --> F1["Protect from changes"] G --> G1["Check direct ownership"] H --> H1["Sort into categories"]
π You Did It!
You now have a complete toolbox for working with objects in JavaScript:
- π keys/values β Peek at labels or contents
- π entries/fromEntries β Convert back and forth
- π¦ assign β Copy and merge
- ποΈ create β Build from blueprints
- π freeze/seal β Protect your data
- β hasOwn β Check true ownership
- ποΈ groupBy β Organize into categories
Youβre now an Object Method Master! π
