Charles Yeung
Charles Yeung

Reputation: 38795

jQuery: converting a select box value and text to an object

I want to convert a select box value and text to an object, below is what I have tried. The result is not like what I wanted, any ideas?

Thanks

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 code:

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)

Result:

[
    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 "
    }
]

Expected result:

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

Upvotes: 0

Views: 414

Answers (2)

PSL
PSL

Reputation: 123739

Try this way:

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

Reason is that you need to set up the keys for the object. if you use a1 as property name in the object literal it itself becomes the key not the value of it. So you can use obj[key] literal.

Full Code

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

Upvotes: 2

Kevin Nacios
Kevin Nacios

Reputation: 2853

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)

Upvotes: 4

Related Questions