Json jquery how to access a value

Hello!

I am trying to access a value in a json object and can’s figure out how, I do an ajax request using jquery abnd get the data in this form


{
   "results" : [
      {
         "components" : [
            {
               "name" : "2203A",
               "short_name" : "2203A",
               "type" : [ "comname" ]
            },
            {
               "long_name" : "Component default",
               "short_name" : "Component Default",
               "type" : [ "comrouter" ]
            },
            {
               "long_name" : "3456",
               "short_name" : "34",
               "types" : [ "comcomute" ]
            }, etc...

how could I access the long_name value in comcomute which should give me 3456, I have been trying several ways but all give me undefined, I tried things like response[‘results’][‘components’] etc. and also response.results.components but nothing works, I am obviously doing something wrong but I am learning and can’t figure out how to, can someone give me an example?

You have to think from an index perspective when dealing with all types of arrays especially with your JSON array, to simply the logic you got the first part right where you access the results array but then inside that you have multiple arrays by the look of it so you would need to call index 0 of the array which equals to components. See the below example:

// Ajax request response
var arr = [],
    res = response,
    com = res.results[0].components;

// Get the value "long_name" from the long_name key
for (var i = 0, max = com.length; i < max; i++) {
    // Caching...
    var _this = com[i];

    if (typeof _this.long_name !== 'undefined') {
        arr.push(_this.long_name);
    }
}

// Aler the results of the loop
alert('Found: ' + arr.join(', '));

// Alert just the "long_name" property with a value of "3456"
alert(com[2].long_name);

Thank you for your help, after trying for so long I got what I needed, I was pulling out my hair