jQuery $.each() - Array of Objects

2020-06-13 06:28发布

I am trying to perform jQuery each function on something like:

"RelatedDoc": [
    {
        "Id": "test",
        "Number": "26262316"
    }
],

Which is a part of a large JSON object. So far I have:

$.each($('#panel_MRD').data('obj'), function (key,value) {
    $('select.mrdDisplayBox').addOption( key, value, false);
});

I am trying to get the option to display "ID - NUMBER" - Any ideas? The above displays but not the right format.

标签: jquery arrays
4条回答
一纸荒年 Trace。
2楼-- · 2020-06-13 06:40
$.each($('#panel_MRD').data('obj'), function (key,value) {
    $('select.mrdDisplayBox').addOption( value.Id, value.Id + ' - ' + value.Number, false);
});
查看更多
Melony?
3楼-- · 2020-06-13 06:51

Here is my problem and what i solved. Use firebug. this is Array Object. Which is use to create four check boxes.

[
    {"datamet":"1","vchAmenityName":"TV"},
    {"datamet":"2","vchAmenityName":"Cable TV"},
    {"datamet":"5","vchAmenityName":"Internet"},
    {"datamet":"7","vchAmenityName":"Air Conditioning"}
]

<input type="checkbox" value="1" id="datamet1" />
<input type="checkbox" value="2" id="datamet2" />
<input type="checkbox" value="5" id="datamet5" />
<input type="checkbox" value="7" id="datamet7" />

i have to find this inside first. Means to check the element inside it like below [{"datamet":"2"}]

For this i did following .. i got the problem solved

$.each(result, function(idx, obj){ 
    $.each(obj, function(key, value){
        console.log(key + ": " + value);
    });
});
查看更多
爷的心禁止访问
4楼-- · 2020-06-13 06:55
$.each(largeJSONobject.ReleatedDoc, function (index,value) {
    $('select.mrdDisplayBox').addOption(value.Id, value.Id + ' - ' + value.Number, false);
});

Your value is the single element from your array: { Id: '', Number: '' }

Documentation is here: http://api.jquery.com/jQuery.each/

查看更多
冷血范
5楼-- · 2020-06-13 06:55

option 1 (this uses the key as the option 'id' i.e. 1, 2, 3 etc):

$.each($('#panel_MRD').data('obj'), function (key,value) {
    $('select.mrdDisplayBox').addOption(key, value.Id + ' - ' + value.Number, false);
});

have not tested, so potentially rushed answer.

[edit] - had a quick look back at this as i realised that there are potentially 2 values that you could use as the option 'id', either key or value.Number.

option 2 (this uses value.Number as the option 'id' i.e. 26262316):

$.each($('#panel_MRD').data('obj'), function (key,value) {
    $('select.mrdDisplayBox').addOption(value.Number, value.Id + ' - ' + value.Number, false);
});

will stop thinking now... :-)

查看更多
登录 后发表回答