简体   繁体   中英

Add options to select using a object's key and values in javascript?

I need to iterate the folowing object in javascript in order to populate a select option:

{"options":{"116":{"pt":"116","en":"116"},"118":{"pt":"118","en":"118"}}}

My actual code is this:

for (var key in data) {
   if (data.hasOwnProperty(key)) {
      var opt = document.createElement('option');
      opt.innerHTML = data[key];
      opt.value = data[key];
      sel.appendChild(opt);
   }
}

The above loop gives me all of the elements in the array. But what i want to do is to only pick the value of the 'pt' keys. My loop must return only 116 and 118 from the 'pt' keys.

You can do something like this using Object.values and forEach :

 const data = {"options":{"116":{"pt":"116","en":"116"},"118":{"pt":"118","en":"118"}}} const sel = document.getElementById('select'); const ptValues = Object.values(data.options) .forEach(v => { var opt = document.createElement('option'); opt.innerHTML = opt.value = v.pt sel.appendChild(opt); }) 
 <select id="select"></select> 

You just need to do data[key].pt :

 var obj = { "options": { "116": { "pt": "116", "en": "116" }, "118": { "pt": "118", "en": "118" } } }; var data = obj.options; var sel = document.getElementById('select'); for (var key in data) { if (data.hasOwnProperty(key)) { var opt = document.createElement('option'); opt.innerHTML = data[key].pt; opt.value = data[key].pt; sel.appendChild(opt); } } 
 <select id="select"></select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM