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).lengthChallenge
EasyWrite 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:
totalItems: The total number of unique items (number of keys)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).lengthTry it yourself
function analyzeShoppingCart(cart) {
// Write code here
return {
totalItems: totalItems,
totalQuantity: totalQuantity,
};
}
// Do not write anything outside functionThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys