如何使用js构建这样的JSON?

时间:2017-12-05 05:56:59

标签: javascript json

我正在尝试构建这样的JSON并通过表单发送服务器。所有这些json值都来自UI中的选择选项。

 {  
   "pages":[  
      {  
         "id":"messages",
         "name":"yourinbox",
         "value":"ACTIVE"
      },
      {  
         "id":"emails",
         "name":"newmail",
         "value":"INACTIVE"
      }
   ]
} 

我已尝试使用以下代码,但我无法获得正确的格式。     有帮助吗?谢谢!

var self = this;
var request = new HttpRequest();
this.form$ = $(selector);
self.form$.find('.loader').hide();

this.onSubmit = function(e){
hideSubmit();
e.preventDefault();
e.stopPropagation();
var parsedata = {};
var data = {};
var selectedOptions = self.form$.find('select');
for (var i = 0, ii = selectedOptions.length; i < ii; ++i) {
var input = selectedOptions[i];
data["name"] = input.id;
data["value"] = input.value;
parsedata.push(data); } };

1 个答案:

答案 0 :(得分:0)

这是粗略的做法;随意即兴发挥。

let object = {"pages" : []};

let options = document.getElementsByTagName("option");

for(i=0;i<options.length; i++) {
  object["pages"][i] = {}
  object["pages"][i]["id"] = options[i].getAttribute('id');
  object["pages"][i]["value"] = options[i].getAttribute('value');
  let activeStatus = options[i].getAttribute('selected');
  if(activeStatus == "true") object["pages"][i]["activeStatus"] = activeStatus;
  else object["pages"][i]["activeStatus"] = false;
}

console.log(object)
<select>
<option id="1" value="One" selected=true>One</option>
<option id="2" value="Two">Two</option>
<option id="3" value="Three">Three</option>
<option id="4" value="Four">Four</option>
</select>