skip to content
Nikolas Barwicki - Javascript Blog Nikolas's Blog

Transform objects using array methods

/ 2 min read

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.