Jquery select返回对象

时间:2016-06-09 08:58:20

标签: jquery select

这是我试图操纵数组并在select中附加选项的小提琴。

FIDDLE

我希望select有AMC,EW,COUPONS的描述,它的各自值为VAS_1000,VAS_1001,VAS_1002

以下是经过验证的代码

     a= o.tuple.map(function(val){
     var inner = val['old']['MST_VAS_TYPE'];
     var ret = {};
     ret[inner["MST_VAS_TYPE_ID"]] = inner['VAS_TYPE_NAME'];
     return ret;
     })

     $.each(a, function(key, value) {   
             $('#fldType')
          .append($('<option>', { value : key })
      .text(value)); 
});

1 个答案:

答案 0 :(得分:1)

您正在使用 Array#map() 生成数组,而是使用 Array#forEach() 生成对象

var a = {};
o.tuple.forEach(function(val) {
  var inner = val['old']['MST_VAS_TYPE'];
  a[inner["MST_VAS_TYPE_ID"]] = inner['VAS_TYPE_NAME'];
})

$.each(a, function(key, value) {
  $('#fldType')
    .append($('<option>', {
        value: key
      })
      .text(value));
});

&#13;
&#13;
var o = {
  "tuple": [{
    "old": {
      "MST_VAS_TYPE": {
        "MST_VAS_TYPE_ID": "VAS_1000",
        "VAS_TYPE_NAME": "AMC",
        "VAS_TYPE_DESC": "Annual Maintenance Contract",
        "CREATED_ON": null,
        "CREATED_BY": null,
        "MODIFIED_ON": null,
        "MODIFIED_BY": null,
        "@xmlns": "http://services.vw.com/lpms/1.0/wsapp"
      }
    },
    "@xmlns": "http://services.vw.com/lpms/1.0/wsapp"
  }, {
    "old": {
      "MST_VAS_TYPE": {
        "MST_VAS_TYPE_ID": "VAS_1001",
        "VAS_TYPE_NAME": "EW",
        "VAS_TYPE_DESC": "Extended Warranty",
        "CREATED_ON": null,
        "CREATED_BY": null,
        "MODIFIED_ON": null,
        "MODIFIED_BY": null,
        "@xmlns": "http://services.vw.com/lpms/1.0/wsapp"
      }
    },
    "@xmlns": "http://services.vw.com/lpms/1.0/wsapp"
  }, {
    "old": {
      "MST_VAS_TYPE": {
        "MST_VAS_TYPE_ID": "VAS_1002",
        "VAS_TYPE_NAME": "COUPON",
        "VAS_TYPE_DESC": "Recall",
        "CREATED_ON": null,
        "CREATED_BY": null,
        "MODIFIED_ON": null,
        "MODIFIED_BY": null,
        "@xmlns": "http://services.vw.com/lpms/1.0/wsapp"
      }
    },
    "@xmlns": "http://services.vw.com/lpms/1.0/wsapp"
  }],
  "@xmlns:SOAP": "http://schemas.xmlsoap.org/soap/envelope/",
  "@xmlns": "http://services.vw.com/lpms/1.0/wsapp"
};

a = {};
o.tuple.forEach(function(val) {
  var inner = val['old']['MST_VAS_TYPE'];
  a[inner["MST_VAS_TYPE_ID"]] = inner['VAS_TYPE_NAME'];
})

$.each(a, function(key, value) {
  $('#fldType')
    .append($('<option>', {
        value: key
      })
      .text(value));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="fldType" class="form-control" data-bind="value:MST_VAS_TYPE_ID"></select>
&#13;
&#13;
&#13;