循环通过Json数组和对象

时间:2022-02-25 01:58:49

I'm trying to pull option information from the Edmunds.com API but I'm having issues with trying to cycle through it and display only what I want. Here is the 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
}

So what I want is to list all the "names" and "values" from "attributes"

所以我想要的是列出“属性”中的所有“名称”和“值”

Here is my code:

这是我的代码:

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

I thought this would look through the "attributes" array but all it returns is the first item name correctly and the value returns 6 instead of 10 and doesn't print anything else.

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

I'm not a jQuery/javascript expert by far and I seem to be missing something here and have tried for 3 days and 100's of solutions, but clearly I'm missing something. I'd appreciate any help or feed back in trying to solve this!!

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

Thanks in advance!

提前致谢!

2 个解决方案

#1


1  

this should work

这应该工作

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

so, after that you would do your stuff like:

所以,之后你会做你喜欢的东西:

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

#2


1  

Note that there are two arrays involved: equipment and attributes. So you could iterate through both of them.

请注意,涉及两个阵列:设备和属性。所以你可以迭代它们。

For inserting the HTML I would suggest to collect first the pieces of HTML in a variable and then insert those in one go with insertHTML. This way the HTML is consistent, and you can create one ul only, instead of creating as many ul as there are li.

为了插入HTML,我建议首先在变量中收集HTML片段,然后使用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>");

I have used forEach instead of the jQuery $.each.

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

You probably want to insert some other HTML for each iteration of the outer loop, or you'll get all attributes listed in one list without distinction of the equipment they are for.

您可能希望为外部循环的每次迭代插入一些其他HTML,或者您将获得列在一个列表中的所有属性,而不区分它们所用的设备。

Maybe something like this:

也许是这样的:

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

That will show the equipment as a list, giving its name and type, and for each there is a nested, indented list with the attributes.

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

#1


1  

this should work

这应该工作

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

so, after that you would do your stuff like:

所以,之后你会做你喜欢的东西:

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

#2


1  

Note that there are two arrays involved: equipment and attributes. So you could iterate through both of them.

请注意,涉及两个阵列:设备和属性。所以你可以迭代它们。

For inserting the HTML I would suggest to collect first the pieces of HTML in a variable and then insert those in one go with insertHTML. This way the HTML is consistent, and you can create one ul only, instead of creating as many ul as there are li.

为了插入HTML,我建议首先在变量中收集HTML片段,然后使用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>");

I have used forEach instead of the jQuery $.each.

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

You probably want to insert some other HTML for each iteration of the outer loop, or you'll get all attributes listed in one list without distinction of the equipment they are for.

您可能希望为外部循环的每次迭代插入一些其他HTML,或者您将获得列在一个列表中的所有属性,而不区分它们所用的设备。

Maybe something like this:

也许是这样的:

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

That will show the equipment as a list, giving its name and type, and for each there is a nested, indented list with the attributes.

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