You can use the Object.keys()
function to get the list of keys from an object.
There are other similar functions as well that you can use such as Object.values()
or Object.entries()
.
As far as your use case is concerned try any one of the solutions mentioned below:
${data.languages[Object.keys(data.languages)[0]]}
// The `0` index can be replaced with i if using a loop.
${Object.values(data.languages)[0]}
You can write as Object.values(data.languages)
which would give you values of object.
I am using the REST Countries API to retrieve data from different countries, the point is to generate a HTML code to insert, depending on the country data.
But as I’m trying to point the language data in my HTML code, it of course returns me an object.
Here are two examples of the data from the API:
languages: {cat: 'Catalan'}
languages: {fra: 'French'}
The line of code in my HTML:
<p class="country__row"><span> ️</span>${data.languages}</p>
I would like to retrieve the values of the first field in those objects (Catalan or French) without having to, of course, write ${data.languages.fra}
in my HTML code.
Thank you for your help.
I tried ${data.languages[0]}
and ${data.languages[0].value}
, doesn’t work.
What is the API you are using? I’m at least a bit confused that it returns data where both key and value actually represent values. That’s something I would consider really bad API design as it creates challenges and issues like the one you are facing here… Thinking a bit further: what happens if there are multiple properties and the object that could appear in any order — which one would be the correct one then?