Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create json by JavaScript for loop?

I have array of select tag.

<select id='uniqueID' name="status">       <option value="1">Present</option>       <option value="2">Absent</option>  </select> 

and I want to create a json object having two fields 'uniqueIDofSelect and optionValue' in JavaScript.

I use getElementsByName("status") and I iterate on it.

EDIT

I need out put like

[{"selectID":2,"OptionValue":"2"}, {"selectID":4,"optionvalue":"1"}] 

and so on...

like image 901
Vikas Avatar asked May 28 '09 13:05

Vikas


People also ask

How do you create a JSON in JavaScript?

var obj = new Object(); obj.name = "Raj"; obj. age = 32; obj. married = false; //convert object to json string var string = JSON. stringify(obj); //convert string to Json Object console.

Can you create JSON file in JavaScript?

Writing to a JSON file: We can write data into a JSON file by using the node. js fs module. We can use writeFile method to write data into a file.

Can I use loop in JSON?

Looping Using JSON It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values.


1 Answers

From what I understand of your request, this should work:

<script> //  var status  = document.getElementsByID("uniqueID"); // this works too var status  = document.getElementsByName("status")[0]; var jsonArr = [];  for (var i = 0; i < status.options.length; i++) {     jsonArr.push({         id: status.options[i].text,         optionValue: status.options[i].value     }); } </script> 
like image 164
donohoe Avatar answered Sep 20 '22 09:09

donohoe