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.
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.
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.
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
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 objectslet 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 objectObject.freeze(person); person.major = 'Software'; // Error! Cannot add properties to a frozen object
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
Execution Result