본문으로 건너뛰기

Advanced Object Methods

Advanced Object Methods

JavaScript objects are an important tool for effectively structuring and managing data. While we previously looked at the basics of using objects, this time we'll focus on some useful methods related to objects.


Object.keys(obj)

This method returns all the keys of an object as an array.

let person = {
name: 'Jimin',
age: 28,
city: 'Seoul',
};

let keys = Object.keys(person);
console.log(keys); // ["name", "age", "city"]

Object.values(obj)

Returns all the values of an object as an array.

let values = Object.values(person);
console.log(values); // ["Jimin", 28, "Seoul"]

Object.entries(obj)

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

let entries = Object.entries(person);
console.log(entries);
// [["name", "Jimin"], ["age", 28], ["city", "Seoul"]]

Practical Use Case: Iterating Through an Object

When you want to perform tasks by iterating through each property of an object, Object.keys or Object.entries can be very useful.

Example: Print all values of an object

for (let key of Object.keys(person)) {
console.log(person[key]);
}

// Or

for (let [key, value] of Object.entries(person)) {
console.log(value);
}

Other Useful Methods

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

    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 properties can no longer be added, removed, or changed.

    Object.freeze(person);
    person.country = 'Korea'; // Error! You cannot add properties to a frozen object.

Conclusion

The object methods provided by JavaScript help to perform a variety of tasks related to objects with ease. Getting familiar with these basic methods early on in your learning will greatly assist in effectively utilizing objects!