views:

130

answers:

2

I know how to create simple object and add dynamically properties to it. object = new Object(); object.someproperty = "";

However, I'm having hardtime creating dynamically something like this: (in javascript)

var datasets = {
        "usa": {
            label: "USA",
            data: [[1988, 483994], [1989, 479060], [1990, 457648], [1991, 401949], [1992, 424705], [1993, 402375], [1994, 377867], [1995, 357382], [1996, 337946], [1997, 336185], [1998, 328611], [1999, 329421], [2000, 342172], [2001, 344932], [2002, 387303], [2003, 440813], [2004, 480451], [2005, 504638], [2006, 528692]]
        },        

        "uk": {
            label: "UK",
            data: [[1988, 62982], [1989, 62027], [1990, 60696], [1991, 62348], [1992, 58560], [1993, 56393], [1994, 54579], [1995, 50818], [1996, 50554], [1997, 48276], [1998, 47691], [1999, 47529], [2000, 47778], [2001, 48760], [2002, 50949], [2003, 57452], [2004, 60234], [2005, 60076], [2006, 59213]]
        },
   .......................
      .............(more...)       
    };
+3  A: 
dataset[country] = {label: countryName, data: theDataObject};

with

var country = 'usa';
var countryName = 'USA';
var theDataObject = [[1988, 483994], [1989, 479060], [1990, 457648], [1991, 401949], [1992, 424705], [1993, 402375], [1994, 377867], [1995, 357382], [1996, 337946], [1997, 336185], [1998, 328611], [1999, 329421], [2000, 342172], [2001, 344932], [2002, 387303], [2003, 440813], [2004, 480451], [2005, 504638], [2006, 528692]];

This is the JSON format.

dataset.usa.label = 'USA';

or dataset.usa.label = countryName; // etc

And :

dataset['usa']

is equal to

dataset.usa

which is equal to

dataset[country]

when the country variable is 'usa'.

Fabien Ménager
A: 

Using the JSON notation as you demonstrate should work. It's just a matter of figuring out your syntax.

The notation allows you to create pretty complex structures in one statement:

var continent = {
  name: "North America",
  countries: [
    { name: "USA",
      states: ['AL', 'AK', 'AZ', ... ]
    },
    { name: "Canada",
      states: ['Ontario', 'Quebec', ... ]
    }    
  ]
}

And so on.

By the way, this also allows you to use the following shorthand for creating blank Objects:

var myObj = {};
levik