How to select a property inside of an object dynamically in JavaScript?

I am using an api from the public-apis from github and it basically gives information about the country that we request
Now I have encountered a problem and I don’t really know how to figure it out
I want to create a card based on the information on the api but I want to do it dynamically and not hardcoding the information inside of the api

This is the structure of the api:
{
other properties,
languages: { eng: "English" },
other properties
}

When I change the country, the eng object inside of the languages object also changes, the example above is for the USA while when I try to get the information for Portugal, I get this:

{
other properties,
languages: { por: "Portugese" },
other properties
}

So the name of the object inside of the languages object changes

How can I select that object inside of languages dynamically? I mean surely I can select them like this:

obj.languages.eng for USA and obj.languages.por for Portugal, but how can I select it dynamically and not hardcoding it myself?

I even searched about getting a property in an object by its index but I found out there is no such thing like index in objects in comparison to arrays

>Solution :

That’s an unfortunate choice for that API designer to have made. Object properties should be consistent. langKey ("eng", "por") and langName ("English", "Portuguese") properties would have been more useful. If you can change the API, I’d suggest doing that.

If not:

…but how can I select it dynamically and not hardcoding it myself?

If the object always has just a single property, you can get the value by using the first (only) element of the iterable returned by Object.values:

const [value] = Object.values(obj.languages);

Examples:

function test(obj) {
    const [value] = Object.values(obj.languages);
    console.log(value);
}

test({ languages: { eng: "English" } });
test({ languages: { por: "Portugese" } });

In a comment you asked:

What if we had multiple values inside of that object that we needed to look for?

If there may be multiple properties, you need some way to knowing which property/properties have the values you want and which ones don’t. Without specifics, I can only point you at the various tools to interrogate an object’s properties, such as Object.values above, Object.entries, Object.keys, Object.getOwnPropertyNames… But it really depends on what you know about the structure. It’s a very unfortunate choice for an API design.

Leave a Reply