簡體   English   中英

遍歷Json數組和對象

[英]Looping through Json Array and Object

我正在嘗試從Edmunds.com API中提取選項信息,但是在嘗試循環瀏覽並僅顯示所需內容時遇到了問題。 這是JSON

{
"equipment": [{
    "id": "200477525",
    "name": "Premium",
    "equipmentType": "AUDIO_SYSTEM",
    "availability": "STANDARD",
    "attributes": [{
        "name": "Total Number Of Speakers",
        "value": "10"
    }, {
        "name": "Digital Audio Input",
        "value": "USB with external media control"
    }, {
        "name": "Memory Card Slot",
        "value": "memory card slot"
    }, {
        "name": "Antenna Type",
        "value": "diversity"
    }, {
        "name": "Cd Player",
        "value": "single CD player"
    }, {
        "name": "Cd Mp3 Playback",
        "value": "CD MP3 Playback"
    }, {
        "name": "Speed Sensitive Volume Control",
        "value": "speed sensitive volume control"
    }, {
        "name": "Usb Connection",
        "value": "USB connection"
    }, {
        "name": "Radio Data System",
        "value": "radio data system"
    }, {
        "name": "Radio",
        "value": "AM/FM"
    }, {
        "name": "Satellite Radio",
        "value": "satellite radio"
    }, {
        "name": "Months Of Provided Satellite Radio Service",
        "value": "3"
    }]
}],
"equipmentCount": 1
}

所以我要列出“屬性”中的所有“名稱”和“值”

這是我的代碼:

function OptionsAudio(styleID){
$.ajax({
    url: "https://api.edmunds.com/api/vehicle/v2/styles/" + styleID + "/equipment?availability=standard&equipmentType=AUDIO_SYSTEM&fmt=json&api_key=<%= ENV["EDMUNDS_API_KEY"] %>",// setting styleID number in URL with passed variable
    //force to handle it as text
    dataType: "text",
    success: function(data) {
        var json = JSON.parse(data);
        var element = document.querySelector("trix-editor"); // get the trix-editor instance and set to element
            element.editor.insertHTML("<strong>Audio Options</strong>");
            $.each(json.equipment, function(index, value){ // iterate though the array
                element.editor.insertHTML("<ul><li>" + json.equipment[0].attributes[0].name + " : " + json.equipment[0].attributes[0].value + "</li></ul>");
                element.editor.insertLineBreak(); // creates a new line 
            });
            element.editor.deleteInDirection("backward");           
}});
}   

我以為這會通過“屬性”數組進行查找,但它返回的只是正確的第一個項目名稱,並且該值返回6而不是10,並且不會打印其他任何內容。

我到目前為止還不是jQuery / javascript專家,我似乎在這里丟失了一些東西,並嘗試了3天和100多個解決方案,但是顯然我缺少了一些東西。 我將不勝感激,也樂意為您解決此問題提供反饋!!

提前致謝!

這應該工作

var attributes = [].concat.apply([], json.equipment.map(function(v) { return v["attributes"]||[] }));

因此,之后您將執行以下操作:

$.each(attributes, function(index, value){ // iterate through the array
    element.editor.insertHTML("<ul><li>" + value.name + " : " + value.value + "</li></ul>");
    element.editor.insertLineBreak(); // creates a new line 
});

請注意,涉及兩個數組: equipmentattributes 這樣您就可以遍歷兩個對象。

對於插入HTML,我建議首先將HTML片段收集到一個變量中,然后與insertHTML一起insertHTML 這樣,HTML是一致的,並且您只能創建一個ul ,而不是創建與li一樣多的ul

var html = [];
json.equipment.forEach(function(equipment){ // iterate through first array
    equipment.attributes.forEach(function(attribute){ // iterate through second array
        html.push("<li>" + attribute.name + " : " + attribute.value + "</li>");
    });
});
element.editor.insertHTML("<ul>" + html.join('\n') + "</ul>");

我使用了forEach而不是jQuery $.each

您可能想為外循環的每次迭代插入一些其他HTML,或者將所有屬性都列在一個列表中,而無需區分它們的用途。

也許是這樣的:

var html = json.equipment.map(function(equipment){ // iterate through first array
    var subhtml = equipment.attributes.map(function(attribute){ // iterate through second array
        return "\n<li>" + attribute.name + " : " + attribute.value + "</li>";
    });
    return "\n<li>" + equipment.name + " : " + equipment.equipmentType 
                     + "<ul>" + subhtml.join('') + "</ul></li>";
});

element.editor.insertHTML("<ul>" + html.join('\n') + "</ul>");

它將以列表形式顯示設備,並提供其名稱和類型,並且每個設備都有一個嵌套的縮進列表及其屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM