Advanced Object Methods
JavaScript objects are an essential data type that allows you to structure and manage data effectively.
This time, let's explore the basic methods for handling keys, values, and properties of objects.
Object.keys(obj)
This method returns an array of all the keys of an object.
const person = {
name: 'Jane',
age: 28,
city: 'New York',
};
const keys = Object.keys(person);
console.log(keys); // ["name", "age", "city"]
Object.values(obj)
This method returns an array of all the values of an object.
const person = {
name: 'Jane',
age: 28,
city: 'New York',
};
const values = Object.values(person);
console.log(values); // ["Jane", 28, "New York"]
Object.entries(obj)
This method returns an array of the object's key-value pairs.
const person = {
name: 'Jane',
age: 28,
city: 'New York',
};
const entries = Object.entries(person);
console.log(entries);
// [["name", "Jane"], ["age", 28], ["city", "New York"]]
Usage Example: Iterating Over an Object
When you want to perform operations while iterating over each property of an object, Object.keys
or Object.entries
can be very useful.
Example: Print all values of an object
const person = {
name: 'Jane',
age: 28,
city: 'New York',
};
for (let key of Object.keys(person)) {
console.log(person[key]);
}
// or
for (let [key, value] of Object.entries(person)) {
console.log(value);
}
Other Object-Related Methods
-
Object.assign(target, ...sources)
: Copies all enumerable properties from one or more source objects to a target object. Returns the target object.Merging objectslet obj1 = { a: 1, b: 2 };
let obj2 = { b: 3, c: 4 };
let merged = Object.assign({}, obj1, obj2);
console.log(merged); // { a: 1, b: 3, c: 4 } -
Object.freeze(obj)
: Freezes an object, preventing new properties from being added or existing properties from being removed or modified.Freezing an objectObject.freeze(person);
person.major = 'Software'; // Error! Cannot add property to frozen object
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.