-1

I want to generate select and options for my project dynamically with array data here I attached what I want and what is the data I have this is data

This is the options I want

]

please help to get solution

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Gowtham S
  • 11
  • 2
  • Welcome to Stack Overflow! Please visit the [help], take the [tour] to see what and [ask]. Do some research - [search SO for answers](https://www.google.com/search?q=javascript+select+options+from+array+site%3Astackoverflow.com). If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [\[<>\]](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Nov 22 '22 at 06:47
  • but I need option value should be like that what I attached in this question eg: you can see 17 has value 14 so step 17 has in html its value should be 14 – Gowtham S Nov 22 '22 at 07:27
  • @GowthamS I added an answer, Hope it will work as per your expectation. – Debug Diva Nov 22 '22 at 11:01

2 Answers2

1

Trickier than it looked

You do not have an array but an object. I renamed it and we can use the Object.entries(stepLabelObject) to loop or reduce.

Filter and map does not work well here.

Reduce

const stepLabelObject = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "", 10:"9", 11: "10", 13: "11", 14: "12", 15: "13", 16: "", 17: "14", 18: "15", 19: "", 20: "16", 21: "17", 22: "", 23: "", 24: "18", 27: "", 28: "", 29: "", 30: "", 31: "", 32: "19", 33: "", 34: "", 35: "", 36: "", 37: "", 38: "", 39: "", 40: "20" };

const stepsDropDown = e => { console.log(e.target.value) };
let cnt = 0;
const options = Object.entries(stepLabelObject).reduce((acc,[key,val]) => {
  if (val !== "") acc.push(`<option value="${key}">step : ${++cnt}</option>`);
  return acc;
});
const sel = document.getElementById('stepDropDown');
sel.innerHTML = options.join('');
sel.addEventListener('change',stepsDropDown);
<select id="stepDropDown"></select>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

First of all, Input data is an object not an array and you can iterate over the object keys with the help of Object.keys() method and then loop over it to create the options dynamically.

Live Demo :

let stepLabelObject = {0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5"};

Object.keys(stepLabelObject).forEach(key => {
  var option = document.createElement("option");
  option.value = key;
  option.text = `Step : ${key}`;
  document.getElementById('stepdropdown').appendChild(option);
});
<select id="stepdropdown" onChange="stepsDropdown()"></select>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123