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
EasyCreate 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:
mostExpensive: the name of the most expensive carcheapest: the name of the cheapest caraveragePrice: 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 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