Tengil
Tengil

Reputation: 19

Javascript - build array in loop

I'm trying to populate an array from a JSON feed. My code looks something like this:

// multiple arrays
var linje_1 = []
var linje_2 = []

// loop from json feed to populate array

for( var i = 0; i < data.length; i++) {
    // I'm trying to "build" the array here. I know for sure that data[i] is good value that match the suffix of the array.
    arrayname = 'linje_'+data[i]; 
    arrayname.push({ label: data[i].x_+''+sid[a]+'', y: data[i].y_+''+sid[a]+'' })
}

Does anybody have any suggestions on how to solve the above?

The problem is that the code will not accept arrayname, but if I change and hardcode linje_1, everything works as expected.

Upvotes: 1

Views: 109

Answers (3)

dfsq
dfsq

Reputation: 193301

When you define a variable arrayname = 'linje_'+data[i]; then its type is String. Strings are not arrays, you can't treat them like array, they don't have array methods.

If you want to dynamically construct the name of the variable, the best thing you can do is to use object and its keys:

var lines = {
    linje_1: [],
    linje_2: []
};

for (var i = 0; i < data.length; i++) {
    var arrayname = 'linje_' + data[i]; 
    lines[arrayname].push({ label: data[i].x_ + sid[a], y: data[i].y_ + sid[a]});
}

Also note, that I cleaned up the code a little (things like data[i].x_ + '' + sid[a] + '').

Upvotes: 3

ktm5124
ktm5124

Reputation: 12123

You're using the same variable for an array and string.

arrayname = 'linje_'+data[i]; 
arrayname.push({ label: data[i].x_+''+sid[a]+'', y: data[i].y_+''+sid[a]+'' })

The variable arrayname is defined as a string, but then you call the push method which is only a method for arrays.

Upvotes: 0

blex
blex

Reputation: 25648

You're pushing data to a String, not an array. Try this:

 window[arrayname].push(/* ... */);

if your variables are declared in the scope of the window, they can be referenced in multiple manners:

myArray
window.myArray
window['myArray'] // You want this one

Upvotes: 0

Related Questions