Object Methods in JavaScript
In JavaScript, objects are the fundamental data structures used to store collections of data and more complex entities. While you can loop through objects using a for...in loop, JavaScript provides a robust set of built-in static methods on the global Object constructor that make manipulating, copying, and iterating over objects powerful and expressive.
Here is a comprehensive guide to the most essential Object methods.
1. Iteration and Data Extraction
Extracting keys and values from an object is a frequent task, especially when transforming data or mapping over object properties.
Object.keys()
Returns an array of a given object's own enumerable string-keyed property names.
const user = { id: 1, name: "Alice", role: "Admin" };
const keys = Object.keys(user);
console.log(keys); // ["id", "name", "role"]
Object.values()
Returns an array of a given object's own enumerable string-keyed property values.
const values = Object.values(user);
console.log(values); // [1, "Alice", "Admin"]
Object.entries()
Returns an array of a given object's own enumerable string-keyed property [key, value] pairs. This is incredibly useful for iterating over an object using array methods.
const entries = Object.entries(user);
console.log(entries);
// [ ["id", 1], ["name", "Alice"], ["role", "Admin"] ]
// Iterating over an object using Object.entries
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}
Object.fromEntries()
The exact inverse of Object.entries(). It takes an iterable (like an array of key-value pairs or a Map) and transforms it back into an object. This is highly useful when combined with .map() or .filter().
const entriesArr = [ ["id", 1], ["name", "Bob"] ];
const newUser = Object.fromEntries(entriesArr);
console.log(newUser); // { id: 1, name: "Bob" }
// Example: Filtering object properties
const scores = { math: 95, english: 80, history: 65, science: 90 };
const highScores = Object.fromEntries(
Object.entries(scores).filter(([subject, score]) => score >= 90)
);
console.log(highScores); // { math: 95, science: 90 }
2. Object Mutation and Copying
Object.assign()
Copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
Before the spread operator (...) existed, this was the primary way to copy or merge objects.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
// Merges source into target (mutates target)
Object.assign(target, source);
console.log(target); // { a: 1, b: 4, c: 5 }
// Cloning an object (without mutating the original)
const original = { x: 10 };
const clone = Object.assign({}, original);
Note: In modern JavaScript, the spread syntax ({ ...obj }) is generally preferred over Object.assign() for shallow cloning and merging.
3. Object Protection and Immutability
JavaScript allows you to lock down objects to prevent unwanted mutations. This is highly beneficial in functional programming and state management architectures (like Redux).
Object.freeze()
Freezes an object: other code cannot delete or change its properties, nor can new properties be added. The object becomes strictly immutable (shallowly).
const config = { apiEndpoint: "https://api.example.com" };
Object.freeze(config);
config.apiEndpoint = "https://hacked.com"; // Fails silently (or throws in Strict Mode)
console.log(config.apiEndpoint); // "https://api.example.com"
Note: Object.freeze() is shallow. If the frozen object contains a nested object, the nested object can still be mutated.
Object.seal()
Seals an object: prevents new properties from being added and marks all existing properties as non-configurable. However, existing property values can still be changed as long as they are writable.
const profile = { username: "js_ninja" };
Object.seal(profile);
profile.username = "ts_ninja"; // Allowed
profile.age = 30; // Ignored/Fails
delete profile.username; // Ignored/Fails
console.log(profile); // { username: "ts_ninja" }
Checking Object State
Object.isFrozen(obj): Returnstrueif frozen.Object.isSealed(obj): Returnstrueif sealed.
4. Property Ownership and Descriptors
Object.hasOwn() (ES2022)
A safe and concise alternative to Object.prototype.hasOwnProperty.call(). It returns true if the specified object has the indicated property as its own property (not inherited through the prototype chain).
const car = { make: "Toyota" };
console.log(Object.hasOwn(car, "make")); // true
console.log(Object.hasOwn(car, "toString")); // false (inherited)
Summary
Mastering Object methods is vital for data manipulation in JavaScript.
- Use
keys(),values(), andentries()to extract data and enable array-like iteration. - Use
fromEntries()to rebuild objects from mapped/filtered arrays. - Rely on
freeze()andseal()to enforce architectural patterns like immutability. - Utilize
hasOwn()for robust property checking.