Menu
Coddy logo textTech

Object Methods

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 17 of 65.

The Object class in JavaScript provides several built-in static methods that help us manipulate and work with objects.

Object.keys(obj) - Returns an array of keys

Object.values(obj) - Returns an array of values

Object.entries(obj) - Returns an array of [key, value] pairs.

For example:

const person = {
    name: "John",
    age: 30,
    city: "New York"
};

const keys = Object.keys(person);
// ["name", "age", "city"]

const values = Object.values(person);
// ["John", 30, "New York"]

const entries = Object.entries(person);
// [["name", "John"], ["age", 30], ["city", "New York"]]

Now you can know how many keys are in an object:

Object.keys(person).length
challenge icon

Challenge

Easy

Write a function named analyzeShoppingCart that takes a shopping cart object. The shopping cart object contains items as keys and their quantities as values. The function should return an object with the following information:

  1. totalItems: The total number of unique items (number of keys)
  2. totalQuantity: The sum of all quantities

Cheat sheet

The Object class provides static methods to work with objects:

<b>Object.keys(obj)</b> - Returns an array of keys

<b>Object.values(obj)</b> - Returns an array of values

<b>Object.entries(obj)</b> - Returns an array of [key, value] pairs

const person = {
    name: "John",
    age: 30,
    city: "New York"
};

const keys = Object.keys(person);
// ["name", "age", "city"]

const values = Object.values(person);
// ["John", 30, "New York"]

const entries = Object.entries(person);
// [["name", "John"], ["age", 30], ["city", "New York"]]

Get the number of keys in an object:

Object.keys(person).length

Try it yourself

function analyzeShoppingCart(cart) {
    // Write code here
    
    
    return {
        totalItems: totalItems,
        totalQuantity: totalQuantity,
    };
}
// Do not write anything outside function
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow