0

我想将选择框值和文本转换为对象,下面是我尝试过的。结果不像我想要的,有什么想法吗?

谢谢

HTML 代码:

<select id="district">
     <option selected="" value="-1"> All </ option>
     <option value="44"> Kowloon Tong </ option>
     <option value="46"> Yau Yat Tsuen </ option>
     <option value="47"> Ho Man Tin </ option>
     <option value="101"> Fei Ngo Shan </ option>
     <option value="133"> Beacon Hill </ option>
</ select>

JS代码:

var a = []
$('#district option').each(function () {
    var a1 = parseInt($(this).attr('value'))
    var a2 = $(this).text()

    var b = {
        a1: a2
    }
    a.push(b)
})
console.log(a)

结果:

[
    Object {
        a1 = " all regions "
    },
    Object {
        a1 = " Kowloon Tong "
    },
    Object {
        a1 = " Yau Yat Chuen "
    },
    Object {
        a1 = " Ho Man "
    },
    Object {
        a1 = " Fei Ngo Shan "
    },
    Object {
        a1 = " Beacon Hill "
    }
]

预期结果:

[
    Object {
        44 = " all regions "
    },
    Object {
        46 = " Kowloon Tong "
    },
    Object {
        47 = " Yau Yat Chuen "
    },
    ...
]
4

2 回答 2

4
var a = []
$('#district option').each(function () {
    var a1 = parseInt($(this).attr('value'))
    var a2 = $(this).text()

    var b = {};
    b[a1] = a2
    a.push(b)
})
console.log(a)
于 2013-06-11T04:15:28.357 回答
2

试试这个方法:

 var b = {};
 b[a1]=a2;
 a.push(b)

原因是您需要为对象设置键。如果您a1在对象文字中用作属性名称,它本身就成为键而不是它的值。所以你可以使用obj[key]文字。

完整代码

var a = []
$('#district option').each(function () {
    var a1 = parseInt(this.value);
    var a2 = $(this).text();
    var b = {};
    b[a1] = a2;
    a.push(b)

})
console.log(a)

演示

于 2013-06-11T04:13:32.277 回答