循环通过Json数组和对象

时间:2016-09-02 22:19:49

标签: javascript jquery json

我正在尝试从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");           
}});
}   

我认为这会查看“attributes”数组,但它返回的只是正确的第一个项目名称,而值返回6而不是10,并且不会打印任何其他内容。

到目前为止,我还不是jQuery / javascript专家,我似乎在这里遗漏了一些东西并尝试了3天和100个解决方案,但显然我错过了一些东西。我很感激任何帮助或反馈,试图解决这个问题!

提前致谢!

2 个答案:

答案 0 :(得分:1)

这应该有效

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 
});

答案 1 :(得分:1)

请注意,涉及两个数组:equipmentattributes。所以你可以遍历它们。

为了插入HTML,我建议首先收集变量中的HTML片段,然后将insertHTML一次性插入。这样,HTML就是一致的,您只能创建一个ul,而不是创建与ul一样多的li

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>");

将设备显示为列表,给出其名称和类型,并且每个设备都有一个带有属性的嵌套缩进列表。