JavaScript offers built-in methods that simplify working with object data. Object.entries(), Object.keys(), and Object.values() help extract and manipulate object properties efficiently.
- Object.keys() returns an array of all property names (keys) of an object.
- Object.values() returns an array of all property values.
- Object.entries() returns an array of key–value pairs, useful for iteration and transformations.
const obj = {
name: 'Prakash',
age: 99,
city: 'Mumbai'
};
console.log(obj);
Object.entries()
The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs.
const entries = Object.entries(obj);
console.log(entries);
Output:
[ [ 'name', 'Prakash' ], [ 'age', 99 ], [ 'city', 'Mumbai' ] ]As you can see, Object.entries(obj) returns an array of arrays, where each inner array contains a key-value pair from the object.
Object.keys()
The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
const keys = Object.keys(obj);
console.log(keys);
Output:
[ 'name', 'age', 'city' ]Object.keys(obj) returns an array containing the keys of the object.
Object.values()
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as provided by a for...in loop.
const values = Object.values(obj);
console.log(values);
Output:
[ 'Prakash', 99, 'Mumbai' ]Object.values(obj) returns an array containing the values of the object.
Practical Use Cases
Summing Values
Suppose you have an object with numerical values, and you want to find the sum of these values. Here's how you can do it:
const obj = {
x: 1,
y: 2,
z: 17
};
const values = Object.values(obj);
const sum = values.reduce((acc, val) => acc + val, 0);
console.log(sum);
Output
20
Checking for Property Existence
You can check if a property exists in an object using the in operator:
const obj = {
name: 'Prakash',
age: 99,
city: 'Mumbai'
};
const isPropertyFound = 'name' in obj;
console.log(isPropertyFound);
const isAgePropertyFound = 'age' in obj;
console.log(isAgePropertyFound);
const isCountryPropertyFound = 'country' in obj;
console.log(isCountryPropertyFound);
Output
true true false
Iterating Over an Object
You can use a for...in loop to iterate over the keys of an object:
const obj = {
name: 'Prakash',
age: 99,
city: 'Mumbai'
};
for (let key in obj) {
console.log(`${key}: ${obj[key]}`);
}