Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add key / value pairs to a global variable in JQuery?

I've got a program that add's a bunch of Div's to a page. I have a bunch of extra 'data-' attributes added to the divs that I later want to include in a global variable.

I basically want to set something up like this:

$.scoreArray = {
    scores: [],
    labels: []
};
$(".word").each(function (i) {
    $.scoreArray.labels.label = $(this).attr("data-label");
    $.scoreArray.labels.x = $(this).attr("data-x");
}
...

but I keep getting the error TypeError: Cannot set property 'label' of undefined

I've tried putting .label and .x as ["label"] and ["x"] but to no avail. What am I doing wrong?

like image 693
McB Avatar asked Dec 04 '25 00:12

McB


1 Answers

Edited: I think I see what you want to do. You want the arrays to contain a bunch of objects, one for each word, which contain the attributes you're collecting. So you want something like:

$.scoreArray = {
    scores: [],
    labels: []
};
$(".word").each(function (i) {
    newLabel = {};
    newLabel.label = $(this).attr("data-label");
    newLabel.x = $(this).attr("data-x");
    $.scoreArray.labels.push(newLabel);
}

However, the error you're seeing sounds like the "global" variable you created isn't being found in the scope you're in. Is this your actual code?

like image 153
Jacob Mattison Avatar answered Dec 06 '25 12:12

Jacob Mattison