-2

I want to create a nested JSON-Object with the following structure:

 [{ 
    "date" : "2011",
    "imgs" : [
        {"path" : "img1.jpg"},
        {"path" : "img2.jpg"},
        {"path" : "img3.jpg"}
        ] 
    },{ 
    "date" : "2012",
    "imgs" : [
        {"path" : "img4.jpg"},
        {"path" : "img5.jpg"},
        {"path" : "img6.jpg"}
    ] 
}]

and so on...

I have a JSON Object with the path to an image and the timestamp. All paths from pictures of 2011 should be saved in the nested 2011 object. All pictures from 2012 in 2012.

But I don't know how I can create the imgs structure...

sumisu
  • 135
  • 1
  • 4
  • 12

2 Answers2

0

jsFiddle Demo

To recreate your exact example you could code it like this:

var json = [];
var imgCount = 1;
var date = 2011;
var imageSets = 2;
for(var i = 0; i < imageSets; i++){
 json.push({ "date":date++, 
  "imgs":(function(){ 
   var set = [];
   for(var n = 0; n < 3; n++){
    set.push({"path":"img"+(imgCount++)+".jpg"});
   }
   return set;})()
 );
}

If you need a more dynamic path then you could have the images in an array, and instead of using imgCount as an exact number you could just reference the stored url in the array. Same could go with date, where instead of date++ it was a reference to a data array where the index was the date variable seen here.

If things get even more complicated, you could always make this structure out of classes.

Travis J
  • 81,153
  • 41
  • 202
  • 273
0

I think it would be better to organize that data this way:

var year2011 = {
  "path1": "img1.jpg",
  "path2": "img2.jpg",
  "path3": "img3.jpg"
}
var year2012 = {
  "path1": "img4.jpg",
  "path2": "img5.jpg",
  "path3": "img6.jpg"
}

It's much simpler. You could write a constructor for the object like this:

var Year = function (path1, path2, path3) {
  this[0] = path1;
  this[1] = path2;
  this[2] = path3;
}

And then call it passing the paths you want to add as arguments:

 var year2013 = new Year("img7.jpg", "img8.jpg", "img9.jpg");

And that would result in this:

year2013 = {
  "path1": "img7.jpg",
  "path2": "img8.jpg",
  "path3": "img9.jpg"
}

And you could also organize that paths like this:

var year2011 = ["img1.jpg","img2.jpg","img3.jpg"],
    year2012 = ["img4.jpg","img5.jpg","img6.jpg"]

NOTE: I have written the years with "year" before because if you write only a number for a variable it would result in an error.

dieortin
  • 514
  • 5
  • 16