Iterating Objects

Object.keys, values, entries

Example

const prices = { pen: 10, book: 250, bag: 899 };
console.log(Object.keys(prices));
console.log(Object.values(prices));
for (const [item, price] of Object.entries(prices)) {
  console.log(`${item}: ₹${price}`);
}
const total = Object.values(prices).reduce((a, b) => a + b, 0);
console.log("Total:", total);

Output

[ 'pen', 'book', 'bag' ]
[ 10, 250, 899 ]
pen: ₹10
book: ₹250
bag: ₹899
Total: 1159

Transforming Objects

Example

Convert to entries, map them, and convert back with Object.fromEntries:

const prices = { pen: 10, book: 250, bag: 899 };
const withGst = Object.fromEntries(
  Object.entries(prices).map(([k, v]) => [k, Math.round(v * 1.18)])
);
console.log(withGst);

Output

{ pen: 12, book: 295, bag: 1061 }