sergserg
sergserg

Reputation: 22224

Trying to add fields to a javascript object

I have a foreach loop (writen using MVC3's Razor engine) and I need to create a new object in the Popups array every iteration. Here's what I'm trying to run:

var popups = [];
var count = 0;

@foreach (var marker in Model) {
    <text>
    popups[count]["content"] = document.createElement("div");
    popups[count]["content"].class = "infobox-custom";
    popups[count]["content"].style.cssText = "padding: 5px; width: 600px;";
    popups[count]["content"].innerHTML = '<div class="professional"><h1>test</h1></div>';

    popups[count]["infobox"] = new InfoBox();

    popups[count]["marker"] = new MarkerInfo();
    count++;
    </text>
}
console.log(popups);

I'm getting the error:

Uncaught TypeError: Cannot set property 'content' of undefined

As you can see, I'm trying to encapsulate each individual marker's related information in a javascript object. I'm aiming to access everything I need by using something like popups[index].marker or popups[index].content.

I'm reading the book Javascript: The Good Parts and there is one part that mentions:

If the object does not already have that property name, the object is augmented:

What am I missing here?

Upvotes: 0

Views: 137

Answers (2)

Musa
Musa

Reputation: 97672

Set popups[count] to an object before you start adding properties to it.

var popups = [];
var count = 0;

@foreach (var marker in Model) {
    <text>
    popups[count] = {};
    popups[count]["content"] = document.createElement("div");
    popups[count]["content"].class = "infobox-custom";
    popups[count]["content"].style.cssText = "padding: 5px; width: 600px;";
    popups[count]["content"].innerHTML = '<div class="professional"><h1>test</h1></div>';

    popups[count]["infobox"] = new InfoBox();

    popups[count]["marker"] = new MarkerInfo();
    count++;
    </text>
}
console.log(popups);

Upvotes: 2

gdoron
gdoron

Reputation: 150243

You need to make popups an array of objects.

popups[count] = {}; // <<<<<<<<<<<<<<<<-----------------------------------
popups[count]["content"] = document.createElement("div");
popups[count]["content"].class = "infobox-custom";
popups[count]["content"].style.cssText = "padding: 5px; width: 600px;";
popups[count]["content"].innerHTML = '<div class="professional"><h1>test</h1></div>';

Upvotes: 1

Related Questions