JavaScript provides several useful methods for working with objects, among which Object.entries()
and Object.values()
are particularly valuable. These methods allow developers to manipulate and iterate over object properties efficiently.
1. Object.entries()
Object.entries()
returns an array of a given object’s own enumerable property [key, value]
pairs. This method is useful when we want to iterate over both the keys and values of an object.
Object.entries(obj);
Example
const user = {
name: 'Alice',
age: 25,
city: 'New York'
};
const entries = Object.entries(user);
console.log(entries);
// Output: [['name', 'Alice'], ['age', 25], ['city', 'New York']]
In the example above, Object.entries(user)
converts the user
object into an array of key-value pairs, making it easier to loop through or manipulate the data.
2. Object.values()
Object.values()
returns an array of a given object’s own enumerable property values. This method is useful when we only need the values of an object without the keys.
Object.values(obj);
Example
const user = {
name: 'Alice',
age: 25,
city: 'New York'
};
const values = Object.values(user);
console.log(values);
// Output: ['Alice', 25, 'New York']
Here, Object.values(user)
extracts just the values from the user
object, providing a simple way to access all property values directly.
3. Other Useful Object Properties
In addition to Object.entries()
and Object.values()
, JavaScript provides other useful methods for working with objects:
Object.keys()
: Returns an array of a given object’s own enumerable property names (keys).
const keys = Object.keys(user);
console.log(keys);
// Output: ['name', 'age', 'city']
Object.assign()
: Copies the values of all enumerable own properties from one or more source objects to a target object.
const target = {};
const source = { a: 1, b: 2 };
Object.assign(target, source);
console.log(target);
// Output: { a: 1, b: 2 }
Object.freeze()
: Prevents new properties from being added to an object, existing properties from being removed, and existing properties from being changed.
const obj = { prop: 42 };
Object.freeze(obj);
obj.prop = 33; // This will not change the value
console.log(obj.prop); // Output: 42