1

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.

1
  • 2
    You're pushing data to a String... 'linje_1' Commented Mar 3, 2015 at 21:15

3 Answers 3

3

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] + '').

Sign up to request clarification or add additional context in comments.

1 Comment

I find this one much cleaner than using window (or a worse possibility, this.) I wrote an almost identical version, but was beat to it by a minute. (Mine differed only in inlining the arrayname variable where it's used.)
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.