我正在尝试从 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 个解决方案,但显然我遗漏了一些东西。如果您能在尝试解决此问题时获得任何帮助或反馈,我将不胜感激!!
提前致谢!
最佳答案
这应该有效
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
});
关于javascript - 循环遍历 Json 数组和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39301384/