Ad

Javascript - How To Loop Through Dict Inside A List

- 1 answer

So I am pretty new when it comes to Javascript and it is as simple as read a json list with a value of:

{
    "URL": [{
            "https://testing.com/en/p/-12332423/": "999"
        }, {
            "https://testing.com/en/p/-123456/": "123"
        },
        {
            "https://testing.com/en/p/-456436346/": "422"
        }
    ]
}

What I would like to do is to have both the URL and the amount of numbers etc

"https://testing.com/en/p/-12332423/" and "999"

and I would like to for loop so it runs each "site" one by one so the first loop should be

"https://testing.com/en/p/-12332423/" and "999"

second loop should be:

"https://testing.com/en/p/-123456/" and "123"

and so on depending on whats inside the json basically.

So my question is how am I able to loop it so I can use those values for each loop?

Ad

Answer

You mean something like this using Object.entries

const data = {
  "URL": [
    {"https://testing.com/en/p/-12332423/": "999"}, 
    {"https://testing.com/en/p/-123456/": "123"},
    {"https://testing.com/en/p/-456436346/": "422"}
  ]
}

data.URL.forEach(obj => { // loop
  const [url, num] = Object.entries(obj)[0]; // grab the key and value from each entry - note the [0]
  console.log("Url",url,"Number", num); // do something with them
})

Ad
source: stackoverflow.com
Ad