jQuery:将选择框值和文本转换为对象

时间:2013-06-11 04:11:23

标签: javascript jquery

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

由于

HTML code:

<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 "
    },
    ...
]

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)

Demo