我有一個JSON對象,它的stringify就像小提琴一樣。JSON對象到jquery select array
http://jsfiddle.net/8TT4p/2289/
我想將其解析到鍵值陣列,這樣我就可以在選擇框中存儲。
下面是我期望有
var convertedArray = {
'VAS_1000' : 'AMC',
'VAS_1001' : 'EW',
'VAS_1002' : 'EW',
}
我有一個JSON對象,它的stringify就像小提琴一樣。JSON對象到jquery select array
http://jsfiddle.net/8TT4p/2289/
我想將其解析到鍵值陣列,這樣我就可以在選擇框中存儲。
下面是我期望有
var convertedArray = {
'VAS_1000' : 'AMC',
'VAS_1001' : 'EW',
'VAS_1002' : 'EW',
}
可以使用Array.prototype.map()
功能。
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.map(function(val){
var inner = val['old']['MST_VAS_TYPE'];
var ret = {};
ret[inner["MST_VAS_TYPE_ID"]] = inner['VAS_TYPE_NAME'];
return ret;
})
sel = document.createElement("select");
document.body.appendChild(sel);
for (var index in a) {
obj = a[index];
for (var prop in obj){
option = document.createElement("option");
option.text = obj[prop];
option.value = prop;
sel.appendChild(option);
}
}
//console.log(a);
當綁定到選擇框時,該值就像0,1,2。這裏是fiddle.http://jsfiddle.net/8TT4p/2293/ – user1650864
@ user1650864我更新了答案。你可以檢查一下嗎? – RRK
只是爲了例如我把字符串div來很容易地得到它變成劇本。
我正在使用eval
將其轉換爲JavaScript對象。
在您必須反對之後,您可以使用for -> in
迭代其屬性,併爲每個option
標記生成html。
最後,將html放入select
標記中。
eval(document.querySelector('div').innerText);
var sel = document.querySelector('select'),
html = '';
for (var item in convertedArray) {
html += '<option value="' + item + '">' + convertedArray[item] + '</option>';
}
sel.innerHTML = html;
<div>
var convertedArray = {
'VAS_1000' : 'AMC',
'VAS_1001' : 'EW',
'VAS_1002' : 'EW',
}
</div>
<select>
</select>
你能分享你所到目前爲止已經試過? – Rajesh