Skip to main content
Practice

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.

Return the keys of the person object as an array
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.

Return the values of the person object as an array
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.

Return the key-value pairs of the person object as a 2D array
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

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);
}

  • Object.assign(target, ...sources): Copies all enumerable properties from one or more source objects to a target object. Returns the target object.

    Merging objects
    let 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 object
    Object.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.