1. ホーム
  2. javascript

[解決済み] JavaScriptのfor loopでjsonを作成するには?

2023-02-03 07:50:52

質問

私は 配列 というselectタグがあります。

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

で、JavaScriptで「uniqueIDofSelectとoptionValue」の2つのフィールドを持つjsonオブジェクトを作りたいのです。

私はgetElementsByName("status")を使って、それを反復しています。

EDIT

以下のような出力が必要です。

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

などなど...

どのように解決するのですか?

あなたの要望を理解する限り、これはうまくいくはずです。

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