Array methods are widely known and used by every JS developer. They are used on daily basis and their usage is really intuitive. Things are getting much worse when it comes to do similar operations with objects. Javascript objects are complex structures and they donβt have corresponding methods for those from arrays.
Object.keys(obj)
Returns array of object keys
const job = {
level: 'senior',
salary: 15000,
}
Object.keys(job) // [ 'level', 'salary' ]
How to check if an object is empty?
const isObjectEmpty = Object.keys(job).length === 0
const emptyObj = {}
const nonEmptyObj = { level: 'senior' }
Object.keys(emptyObj).length === 0 // true
Object.keys(nonEmptyObj).length === 0 // false
Object.values(obj)
Returns array of objectβs values
const job = {
level: 'senior',
salary: 15000,
}
Object.values(job) // [[ 'senior', 15000 ]
How to sum values of objectβs entries
const shoppingList = {
'π«': 9.0,
'π': 4.5,
'π': 2.9,
}
const prices = Object.values(shoppingList) // [ 9, 4.5, 2.9 ]
const total = prices.reduce((sum, price) => sum + price) // 16.4
Object.entries(obj)
Returns array of pairs [key, value]
const job = {
level: 'senior',
salary: 15000,
}
Object.entries(job) // [ [ 'level', 'senior' ], [ 'salary', 15000 ] ]
Iterating through an object
const shoppingList = {
'π«': 9.0,
'π': 4.5,
'π': 2.9,
}
Object.entries(shoppingList).forEach(([key, value]) =>
console.log(`${key}: ${value}`)
)
// 'π«: 9', 'π: 4.5', 'π: 2.9'
How to check if the price is greater than 5?
for (const [fruit, price] of Object.entries(shoppingList)) {
if (price > 5) {
console.log(fruit) // 'π«'
}
}
.map for objects
Objects donβt have corresponding methods for array.map
or array.filter
. Fortunately we can achieve the same result using other methods:
Object.entries(obj)
to get key-value pairs,- use needed array method,
- transforming array back to the object using
Object.fromEntries(arr)
const shoppingList = {
'π«': 9.0,
'π': 4.5,
'π': 2.9,
}
const doublePrices = Object.fromEntries(
Object.entries(shoppingList).map(([key, value]) => [key, value * 2])
)
console.log(doublePrices) // { 'π«': 18, 'π': 9, 'π': 5.8 }
Summary
Using these object methods solves many problems with an object manipulation. We obtain the ease of working with arrays but with much more complex data structures.