-1

I am trying to create a dynamic dropdown using javascript and i am unable to loop in through the values returned from the backend application, The object length is returned as 0 even though I have values on it

Below is the object

enter image description here

and This is the javascript snippet

 for (key in swaggerlist) {
    console.log(key)
    if (!swaggerlist.hasOwnProperty(key)) continue;
      var obj = swaggerlist[key];
        for (var prop in obj) {
          if (!obj.hasOwnProperty(prop)) continue;
            if(params["url"] == obj[prop]){
              option += '<option value="'+ obj[prop] + '" selected>' + obj[prop] + '</option>\n';
          } else {
              option += '<option value="'+obj[prop] + '">' + obj[prop] + '</option>\n';
        }
     console.log(obj[prop])
  }
  }

I am able to read the below one using the above function

enter image description here

How to fix this one and loop in through the object to get the values?

SimbuStar
  • 623
  • 1
  • 7
  • 18

2 Answers2

0

You could use Object.keys to get an array of keys. Then loop over those.

var swaggerKeys = Object.keys(swaggerlist);
swaggerKeys.forEach((key) => {
    //Access property
    var someVal = swaggerlist[key];
});
RickTakes
  • 1,197
  • 1
  • 9
  • 14
0

Because you have to loop on the array in the "interstitials" prop.

You get an object with a interstitials property who contains your items inside an array.

var server_resp = {
  interstitials:["some data","some other data"]
}

server_resp.interstitials.forEach(item => {
  $("#mySelect").append(`<option>${item}</option>`)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mySelect"></select>
Alexis
  • 5,681
  • 1
  • 27
  • 44