Object manipulation: keys, values, entries
π₯ Object.keys, values, entries
π₯ Transforming objects
Object.keys()
, Object.values()
, and Object.entries()
methods provide ways to work with objects by extracting their keys, values, and key-value pairs, respectively.
Object.keys()
: This method returns an array containing the keys of an object.
For example:
const person = {
name: 'John',
age: 30,
city: 'New York'
};
const keys = Object.keys(person);
console.log(keys); // Output: ['name', 'age', 'city']
Object.values()
: This method returns an array containing the values of an object.
For example:
const person = {
name: 'John',
age: 30,
city: 'New York'
};
const values = Object.values(person);
console.log(values); // Output: ['John', 30, 'New York']
Object.entries()
: This method returns an array of arrays, where each inner array contains a key-value pair as [key, value]
.
For example:
const person = {
name: 'John',
age: 30,
city: 'New York'
};
const entries = Object.entries(person);
console.log(entries);
// Output: [['name', 'John'], ['age', 30], ['city', 'New York']]
The above methods are useful for iterating over object properties, performing operations on keys, values, or entries, and manipulating object data in various ways.
To transform objects using methods like map
, filter
, and others similar to arrays, we can follow the below steps:
- Use
Object.entries(obj)
to convert the object into an array of key/value pairs. - Apply array methods such as
map
to transform these key/value pairs. - Finally, use
Object.fromEntries(array)
to convert the transformed array back into an object.
For example:
let prices = {
banana: 1,
orange: 2,
meat: 4,
};
let doublePrices = Object.fromEntries(
Object.entries(prices).map(entry => [entry[0], entry[1] * 2])
);
console.log(doublePrices.meat); // Output: 8