Listing an Object's Keys and Entries

Marta’s rates table now has her home country in it, because [HOME_COUNTRY]: 3.2 puts GB where the bare name used to be. The port can quote postage for any one country. The courier’s booking form wants more than one rate, though. It asks which zones she ships to, as a comma-separated list, and how many there are.

In Python, that’s a job for the dict’s own methods. In this lesson, you’ll get the same keys, values, and pairs out of a JavaScript object, see why the tools for it live somewhere you might not look, and meet the type JavaScript provides for keys that aren’t strings. Start with the zone list.

List the Zones With Object.keys()

The Python script turns the dict into a list of its keys, joins them for the form, and counts them with len():

Language: Python
HOME_COUNTRY = "GB"
RATES = {HOME_COUNTRY: 3.20, "IE": 7.50, "DE": 8.90, "US": 14.50, "ROW": 16.50}
zones = list(RATES)
print(f"Zones: {', '.join(zones)}")
print(f"{len(RATES)} zones")

In JavaScript, you hand the object to Object.keys(), which returns the keys you put in it as an array. From there, .join() and .length work as they do on any array:

Language: JavaScript
const HOME_COUNTRY = "GB";
const RATES = { [HOME_COUNTRY]: 3.2, IE: 7.5, DE: 8.9, US: 14.5, ROW: 16.5 };
const zones = Object.keys(RATES);
console.log(zones);
console.log(`Zones: ${zones.join(", ")}`);
console.log(`${zones.length} zones`);

The zones come back in the order Marta wrote them, ready to paste into the form:

Language: Program Output
[ 'GB', 'IE', 'DE', 'US', 'ROW' ]
Zones: GB, IE, DE, US, ROW
5 zones

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.