0

I got that response from a http request and I want to loop through that to get the properties of each object programatically.

{
   "GLASS": {
           "EUR": 4.89,
           "USD": 6.03
          },
   "COMPUTER": {
          "EUR": 289.66,
          "USD": 426.52
          },
   "TV": {
          "EUR": 3813.06,
          "USD": 5617.77
          }
 }

So I created a for loop to assign the name of each product to a variable and display it in an html page:

for(let i = 0; i < products.length; i++)
{
    var productName = products[i]

   list.innerHTML += "<li><span>"+products[i]+"</span><span>€"+res.data["GlASS"].EUR+"</span><span>$"+res.data.productName.USD+"</span></li>"


}

If i output: res.data["GLASS"].EUR I get the correct value.

If i output: res.data.GLASS.EUR I get the correct value.

If I try res.data.productName.EUR I get undefined

If I try res.data.products[i].EUR I get undefined

How can I, programatically, get the properties of a list of json objects? I have tried many different ways to output the data of one item but it did not work.

EAzevedo
  • 751
  • 2
  • 17
  • 46

1 Answers1

1

Your javascript response json is not an array of the product which you are interpreting in your code,

if you are considering it is an array than it should be like

[
   {"GLASS": {
           "EUR": 4.89,
           "USD": 6.03
          }},
   {"COMPUTER": {
          "EUR": 289.66,
          "USD": 426.52
          }},
   {"TV": {
          "EUR": 3813.06,
          "USD": 5617.77
          }}
 ]

and you can access like,

products[0].GLASS.EUR
programtreasures
  • 4,250
  • 1
  • 10
  • 29