0

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

{
"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.

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!!

Thanks in advance!

3
  • Rather than accessing json.equipment[0], look at value. value should have a property, attributes, which you can iterate through. Commented Sep 2, 2016 at 22:22
  • jQuery is for DOM. Use Array#map and map a function that mutates DOM to every element in original array. Commented Sep 2, 2016 at 22:23
  • @RishatMuhametshin The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object - jQuery.each() | jQuery API Documentation Commented Sep 2, 2016 at 22:44

2 Answers 2

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 
});
Sign up to request clarification or add additional context in comments.

3 Comments

I will try that next!! If you have the time can you explain how it's working, it looks pretty straight forward by reading it, but would like to ensure i not only get this working but understand why, and thank you for fast reply!
the first code just groups every object that is in json.equipment[N].attribures in a variable attributes using Array.concat, the second iterates over that array of attributes
This was great and is usable on all the API calls too! thank you!!! and thank you for the explanation, this answer was the most flexible so I chose it.
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.

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.

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.

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.

3 Comments

This answer too worked, but the one chosen offered a wider array of flexibility, but I up ticked you as it wouldn't let me select 2 answers. Thank you also for the quick response too and the code!
one other note too, the <ul> tags should only be done once but for some reason it doesn't work when writing into "twix-editor" so I found that if I write <ul><li></li></ul> into each item. So if anyone finds this and it helps, great!
Maybe trix-editor will accept the whole <ul> group (with all <li>s in it) to be pasted into it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.