user906849
user906849

Reputation:

How do I create an javascript object dynamically?

I am trying to create an object of locations for placing points on a map.

My code is:

    var Locs = [{}];
    var title = '', content = '';

    for (i = 0; i < locations.length; i++) {


      content = '<div id="bodyContent">' +
                '<p><b>' + locations[i][0] + '</b><br />' +
                locations[i][4] +
                '</div>';

         Locs[i]['lat']   = locations[i][1];
         Locs[i]['lon']   = locations[i][2];
         Locs[i]['zoom']  = zoom;
         Locs[i]['title'] = locations[i][0];
         Locs[i]['html']  = content;

    }

I keep getting an error: TypeError: Locs[i] is undefined If I replace i with 0 it works for displaying one point on the map.

What I need to output is:

var Locs = [
    {
        lat: 45.9,
        lon: 10.9,
        zoom: 3,
        title: 'Title A1',
        html: '<h3>Content A1</h3>'
    },
    {
        lat: 44.8,
        lon: 1.7,
        zoom: 3,
        title: 'Title B1'
        html: '<h3>Content B1</h3>'
    },
    {
        lat: 51.5,
        lon: -1.1,
        zoom: 3,
        title: 'Title C1',
        html: '<h3>Content C1</h3>'
    }
];

So I am wondering if someone can explain to me what I don't understand about creating an object dynamically?

Upvotes: 0

Views: 87

Answers (3)

yeahwhat
yeahwhat

Reputation: 855

As the error states, you are trying to create new keys to an object that is undefined. Before assigning values to an object, you need to create it.

When you do var Locs = [{}];, it creates an array with one empty object, that's why it works when you replace i by 0. You can either add Locs[i] = {}; before assigning the latitude to create an empty object, or directly something like: Locs.push({lat: locations[i][1], long: locations[i][2], ...etc});

Upvotes: 1

DVN
DVN

Reputation: 114

Initiate arrays for each loop. This code will help you:

var Locs = [];
Locs[1] = [];
Locs[1]['lat'] = 123;
Locs[1]['long'] = 123;
Locs[2] = [];
Locs[2]['lat'] = 123;
Locs[2]['long'] = 123;

Upvotes: -1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You have to create a new object first before accessing that,

Locs[i] = {};
Locs[i]['lat']   = locations[i][1];
Locs[i]['lon']   = locations[i][2];
Locs[i]['zoom']  = zoom;
Locs[i]['title'] = locations[i][0];
Locs[i]['html']  = content;

If you do not create it then your code would be evaluated like,

Locs[i]['lat']
undefined['lat'] //will throw error here.

Upvotes: 3

Related Questions