DEV Community

Nikolas ⚡️
Nikolas ⚡️

Posted on • Originally published at nikolasbarwicki.com

Transform objects using array methods

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' ]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Object.values(obj)

Returns array of object's values

const job = {
    level: "senior",
    salary: 15000
};

Object.values(job); // [[ 'senior', 15000 ]
Enter fullscreen mode Exit fullscreen mode

How to sum values of object's entries

const shoppingList = {
    "🫐": 9.00,
    "🍓": 4.50,
    "🍋": 2.90
}

const prices = Object.values(shoppingList); // [ 9, 4.5, 2.9 ]

const total = prices.reduce((sum, price) => sum + price); // 16.4
Enter fullscreen mode Exit fullscreen mode

Object.entries(obj)

Returns array of pairs [key, value]

const job = {
    level: "senior",
    salary: 15000
};

Object.entries(job); // [ [ 'level', 'senior' ], [ 'salary', 15000 ] ]
Enter fullscreen mode Exit fullscreen mode

Iterating through an object

const shoppingList = {
    "🫐": 9.00,
    "🍓": 4.50,
    "🍋": 2.90
}

Object
    .entries(shoppingList)
    .forEach(([key, value]) => console.log(`${key}: ${value}`))
    // '🫐: 9', '🍓: 4.5', '🍋: 2.9'
Enter fullscreen mode Exit fullscreen mode

How to check if the price is greater than 5?

for (const [fruit, price] of Object.entries(shoppingList)) {
  if (price > 5) {
    console.log(fruit); // '🫐'
  }
}
Enter fullscreen mode Exit fullscreen mode

.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.00,
    "🍓": 4.50,
    "🍋": 2.90
}

const doublePrices = Object.fromEntries(
  Object
    .entries(shoppingList)
    .map(([key, value]) => [key, value * 2])
);

console.log(doublePrices) // { '🫐': 18, '🍓': 9, '🍋': 5.8 }
Enter fullscreen mode Exit fullscreen mode

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.

Oldest comments (0)