Menu
Coddy logo textTech

Iterate Over JSON

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

To iterate over the keys of a JSON we can either use Object.keys():

const userSettings = {
	theme: "dark",
	notifications: true
};

const keys = Object.keys(userSettings)
for (let i = 0; i < keys.length; i++) {
	console.log(keys[i], userSettings[keys[i]])
}

Or we can iterate using a for...in loop:

for (const key in userSettings) {
	console.log(key, userSettings[key]);
}

Another way is to use .entries():

for (const [k, v] of Object.entries(userSettings)) {
    // k is the key, v is the value
}
challenge icon

Challenge

Easy

Create a function named analyzeCarData that takes a JSON object as input. The object contains data about a car dealership's inventory where:

  • keys are the car models
  • values are the prices

The function should return an object containing:

  1. mostExpensive: the name of the most expensive car
  2. cheapest: the name of the cheapest car
  3. averagePrice: the average price of all cars

Cheat sheet

To iterate over JSON object keys, use Object.keys():

const keys = Object.keys(userSettings)
for (let i = 0; i < keys.length; i++) {
	console.log(keys[i], userSettings[keys[i]])
}

Or use a for...in loop:

for (const key in userSettings) {
	console.log(key, userSettings[key]);
}

Or use Object.entries() to get key-value pairs:

for (const [k, v] of Object.entries(userSettings)) {
    // k is the key, v is the value
}

Try it yourself

function analyzeCarData(carData) {
    // Write code here
}
// 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