Lecture

Advanced Object Methods

JavaScript objects are an essential data type for effectively structuring and managing data.

Here, we'll look at fundamental methods for handling the 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: 'Emma', age: 28, city: 'New York', }; const keys = Object.keys(person); console.log(keys); // ["name", "age", "city"]

Object.values(obj)

Returns an array of all values of an object.

Return the values of the person object as an array
const person = { name: 'Emma', age: 28, city: 'New York', }; const values = Object.values(person); console.log(values); // ["Emma", 28, "New York"]

Object.entries(obj)

Returns all key-value pairs of an object as a two-dimensional array.

Return key-value pairs of the person object as a two-dimensional array
const person = { name: 'Emma', age: 28, city: 'New York', }; const entries = Object.entries(person); console.log(entries); // [["name", "Emma"], ["age", 28], ["city", "New York"]]

Usage Example: Iterating through an Object

When you want to perform operations on each property of an object, Object.keys or Object.entries can be handy.

Example: Print all values of an object

Print all values of an object
const person = { name: 'Emma', 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); }

Additional Object Methods

  • 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 combined = Object.assign({}, obj1, obj2); console.log(combined); // { a: 1, b: 3, c: 4 }
  • Object.freeze(obj): Freezes an object so that its properties cannot be added, removed, or modified.

    Freezing an object
    Object.freeze(person); person.major = 'Software'; // Error! Cannot add properties to a frozen object
Mission
0 / 1

Which method returns all key-value pairs of an object as a two-dimensional array?

Object.keys(obj)

Object.values(obj)

Object.entries(obj)

Object.freeze(obj)

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run

Execution Result