Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading