Is it possible to create an empty multidimensional array in javascript/jquery?

finferflu picture finferflu · Sep 22, 2011 · Viewed 28.1k times · Source

I am trying to create a very basic Flickr gallery using the Flickr API. What I want to achieve is sorting my pictures by tag. What I am using is jQuery.getJSON() so that I can parse the API response of flickr.photosets.getPhotos.

The data I am interested in getting from Flickr is the tag and the URL associated to each photo. The problem with this is that the only logical way out of this for me is creating a multidimensional array of the following format:

Array['tag1'] => ['URL_1', 'URL_2', 'URL_3', 'URL_n'];

However, I cannot find any way to achieve this. My code looks like this:

$.getJSON('http://api.flickr.com/services/rest/?api_key=xxx&method=flickr.photosets.getPhotos&user_id=xxx&format=json&extras=tags%2C+url_l%2C+url_sq&nojsoncallback=1&photoset_id=xxx', 
   function(data) {

     var imageArray = [];   
     $.each(data.photoset.photo, function(i, item) {

       imageArray[item.tags] = [item.url_sq,];

     });
});

I am aware that the code might look awkward, but I've tried everything and there's no way I can figure this out.

Answer

Raynos picture Raynos · Sep 22, 2011
var arr = [];
arr[0] = [];
arr[0][0] = [];
arr[0][0][0] = "3 dimentional array"

Multi dimentional arrays have a lot of gaps unless they are used properly. A two dimensional array is called a matrix.

I believe your data contains a space seperate string called "tags" containing the tags and a single url.

var tagObject = {};
data.photoset.photo.forEach(function(val) {
  val.tags.split(" ").forEach(function(tag) {
    if (!tagObject[tag]) {
      tagObject[tag] = [];
    }
    tagObject[tag].push(val.url_sq);
  });
});
console.log(tagObject); 
/*
  {
    "sea": ["url1", "url2", ...],
    "things": ["url4", ...],
    ...
  }
*/

I don't know how it returns multiple tags.