-1

This is the select List option

<select name="List" id="List">
        <option value="">-Select-</option>
        <option value="">id1@option1</option>
        <option value="">id2@option2</option>
        <option value="">id3@option3</option>
    </select>

This is my desired results for array to produce this pattern:

opts = [
           ['id1', 'obj', 'option1'],
           ['id2', 'obj', 'option2'],
           ['id3', 'obj', 'option3']
       ];

Note: the string I want to get is this:

id1,obj,option1,img1,id2,obj,option2,img2,id3, obj,option3,img3

Note: the string am getting is this:

id1,obj,option1,img1id2,obj,option2,img2id3,obj,option3,img3

My code:Here i am getting the all option values and splitting them using the @ sign and then passing to the list to an array which i want to produce a pattern

var options = document.getElementById("List");
var opts, opt = "";
var temp = "";
for(var i =1; i <options.length; i++){
    var option=options[i].textContent.split('@');
    var A = option[0];
    var B = option[1];
    //this is the array am producing 
    opt = new Array(new Array(A,'obj',B));

    for(var j= 0; j < opt.length; j++) {
       temp += opt[j];
    }
    opts  = temp;
}

alert(opts);
Mr.mubanga
  • 31
  • 6

1 Answers1

3

To create the array value, iterate the <option> elements (except the first), extract their textContent value and create the appropriate arrays.

Then, flatten the array and join it with commas

const options = [...document.querySelectorAll('#List option')]
  .slice(1) // skip the first
  .map(({ textContent }, i) => {
    const vals = textContent.split('@') // split the text on "@"
    vals.splice(1, 0, 'obj') // insert "obj" at position #1
    vals.push(`img${i + 1}`) // append "imgX". I'm just guessing here
    return vals
  })

const str = options.flat().join(',')

document.body.textContent = str
<select name="List" id="List">
  <option value="">-Select-</option>
  <option value="">id1@option1</option>
  <option value="">id2@option2</option>
  <option value="">id3@option3</option>
</select>
Phil
  • 128,310
  • 20
  • 201
  • 202