1

I have a json file present like so:

{

    "product": {
        images": [
         "13953115",
         "13953112",
         "13953116",
         "13953026",
         "13953021",
         "11519717" 
        ], //etc
   }
}

I'm trying to get only the 4th element (in example above "13953026") and then use it to append to a div. The code currently looks like this:

 $.getJSON('url-to-product?format=json', function(data){
   var images = [];

   // how to select the fourth element?//
   var image = images[4];

   var fourthImage = $('<img src="'+ image +'" width="265" height="340" alt="" />');
   $('.con_images').html(fourthImage);
 });

I thought var image = images[4]; would work but obviously that isn't. I found some usefull posts in here but I don't know how to incorporate that in my code.

Can anybody help me with this? Thx...

Community
  • 1
  • 1
Meules
  • 1,349
  • 4
  • 24
  • 71

2 Answers2

2

I don't see any problem doing this:

$.getJSON('url-to-product?format=json', function(data){

   var image = data.product.images[3];

   var fourthImage = $('<img src="'+ image +'" width="265" height="340" alt="" />');
   $('.con_images').html(fourthImage);
});

Please also see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

idmean
  • 14,540
  • 9
  • 54
  • 83
1

To access the fourth element in your Array,

use obj.product.images[3]

Array index starts from 0

Jayanth
  • 329
  • 4
  • 15