Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse through an array of JSON in javascript? and use it to populate <option> element

I have this array of JSON and I want to loop through them and use it to fill up my option element.

Sample Array:

var myOptionData = [
          {fooValue:"1", fooText:"option A"},
          {fooValue:"2", fooText:"option B"},
          {fooValue:"3", fooText:"option C"}
] 

I did use this method:

var fields="";

 fields += "</select >";

        fields += "<option  value='0'></option>";
        $.each(myOptionData , function (key, value) {
            fields += "<option value=" + value.fooValue + ">" + value.fooText + "</option>";
        });
        fields += "</select >";

//But I want to make it more flexible, so that I can reuse it in making another <option> from another array of JSON, like this scenario:

var myNewOptionData = [
          {myValue:"5", myText:"option E"},
          {myValue:"6", myText:"option F"},
          {myValue:"7", myText:"option G"},
          {myValue:"8", myText:"option H"}
] 

//Now I cannot use the method above

like image 785
Xon Version9 Avatar asked Oct 18 '25 06:10

Xon Version9


1 Answers

Simply turn the whole operation into a function:

function mkSelect(data){
  return "<select><option  value='0'></option>"
   + data.map(o=>{
      let [val,txt]=Object.values(o);
      return "<option value=" + val + ">" + txt + "</option>"}).join("") 
   + "</select >";
}
const myOptionData = [
      {fooValue:"1", fooText:"option A"},
      {fooValue:"2", fooText:"option B"},
      {fooValue:"3", fooText:"option C"}
], 
  myNewOptionData = [
      {myValue:"5", myText:"option E"},
      {myValue:"6", myText:"option F"},
      {myValue:"7", myText:"option G"},
      {myValue:"8", myText:"option H"}
];

document.querySelector("#frm").innerHTML=mkSelect(myOptionData)+"<br>"
   +mkSelect(myNewOptionData); 
<form id="frm"></form>

The function should be improved, as it momentarily relies on the sequence of the properties of object o. Maybe the property names could be checked for containing "Value" and "Text"?

Here is a slight variation of my snippet, checking for parts of the property names. Now the order of the given option properties is immaterial and a selected option can also be defined by providing a property that contains "select" in its name:

function mkSelect(data){
  const arr=data.map(o=>Object.fromEntries(Object.entries(o).map(([k,v])=>
       [k.replace(/.*value.*/i,"val")        // generate an object with standardised key names:
         .replace(/.*text.*/i,"txt")         // ===> val, txt and sel
         .replace(/.*select.*/i,"sel"),
        v])));
  return "<select><option value='0'></option>"  // build the actual select element:
        +arr.map(o=>`<option value="${o.val}"${o.sel?` selected="${o.sel}"`:""}>${o.txt}</option>`).join("")+"</select>"
}
const myOptionData = [
      {fooValue:"1", fooText:"option A"},
      {fooValue:"2", fooText:"option B", thisIsSelected: true},
      {fooValue:"3", fooText:"option C"},
      {thisTextIsGreatToo:"option D", andValueThis:"4"}
], 
  myNewOptionData = [
      {myValue:"5", myText:"option E"},
      {myValue:"6", myText:"option F"},
      {myValue:"7", myText:"option G"},
      {selectThis: 1, myLastText:"option H", myLastValue:"8"}
];

document.querySelector("#frm").innerHTML=mkSelect(myOptionData)+"<br>"+mkSelect(myNewOptionData)
<form id="frm"></form>
like image 100
Carsten Massmann Avatar answered Oct 19 '25 21:10

Carsten Massmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!