LearnFrenzy
Sign in Take a free test

Objects · Objects Coding Problems · Question 4

Invert an object's keys and values in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

Invert a country → code object into a code → country object, and look up a country by its code.

Solution
main.js
const countryCode = { India: "IN", Japan: "JP", Brazil: "BR" };

const codeToCountry = {};
for (const [country, code] of Object.entries(countryCode)) {
  codeToCountry[code] = country;
}

console.log(codeToCountry);
console.log(codeToCountry.JP, codeToCountry["IN"]);

Output Verified by running it on Node.js

{ IN: 'India', JP: 'Japan', BR: 'Brazil' }
Japan India

Object.entries gives each pair; assigning code → country builds the reverse lookup. (Duplicate values would overwrite each other.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links