如何通过JavaScript for循环创建json?

Vik*_*kas 96 javascript json

我有阵列选择标记.

<select id='uniqueID' name="status">
      <option value="1">Present</option>
      <option value="2">Absent</option>
 </select>
Run Code Online (Sandbox Code Playgroud)

我想创建一个json对象,在JavaScript中有两个字段'uniqueIDofSelect和optionValue'.

我使用getElementsByName("status")并迭代它.

编辑

我需要像我一样

[{"selectID":2,"OptionValue":"2"},
{"selectID":4,"optionvalue":"1"}]
Run Code Online (Sandbox Code Playgroud)

等等...

don*_*hoe 169

根据我对您的请求的理解,这应该工作:

<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>
Run Code Online (Sandbox Code Playgroud)

  • JSON是一个对象而不是一个数组. (41认同)
  • `var jsonArr = [];`创建一个新数组.`var jsonObj = {};`创建一个新的Object (18认同)

Jos*_*ola 41

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}
Run Code Online (Sandbox Code Playgroud)


sys*_*USE 8

如果您想要一个JavaScript对象,如下所示:

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }
Run Code Online (Sandbox Code Playgroud)

(其中选项2,"缺席",是当前选择),那么以下代码应该产生它:

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }
Run Code Online (Sandbox Code Playgroud)

如果你想所有这些对象的数组(而不仅仅是选择一个),使用迈克尔的代码,但换出status.options[i].textstatus.id.

如果您想要一个包含所选对象的JSON表示的字符串,请改用:

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }
Run Code Online (Sandbox Code Playgroud)