views:

24

answers:

2

I'm trying to use the userBox plugin and in the example we have the following array being built:

var data = [
    {text: "Adam Adamson",    id: "[email protected]"},
    {text: "Betsy Boop",      id: "[email protected]"},
    {text: "Jooles Jooles",   id: "[email protected]"}
];

I want to build my array at runtime using JSON data I receive from my webservice. In my code I have tried to mimic this array with the following.

    var data = new Array();

    for (var i = 0; i < msg.d.ListExercise.length; i++) {
        $("userlist").append("msg.d.ListExercise[i].exercise_value");
        if (i > 0 && i < msg.d.ListExercise.length - 1) {
            data.push('{text: ' + '"' + msg.d.ListExercise[i].exercise_value + '"' + ' , id: ' + '"' + msg.d.ListExercise[i].exercise_id + '"' + '},');
        }
        if (i == msg.d.ListExercise.length - 1) {
            data.push('{text: ' + '"' + msg.d.ListExercise[i].exercise_value + '"' + ' , id: ' + '"' + msg.d.ListExercise[i].exercise_id + '"' + '}');
        }
    }

From what I understand in the example he building a string array. I have verified that the array is being added to and that the data is being added to it. However, when I pass my array into the plugin code it shows the word 'Undefined' 135 times (the length of the array).

My Array looks something like this:

{text: "Standard Push-Up" , id: "1"},
{text: "Wide Front Pull-Up" , id: "2"},
{text: "Vertical Punches" , id: "135"}

What is the best way to get my data into his array example in javascript?

+2  A: 

You're supposed to be building an array of hashes, not an array of strings that look like hashes. You need something like

data.push({text: msg.d.ListExercise[i].exercise_value, id: msg.d.ListExercise[i].exercise_id });

bemace
+1  A: 

Currently you're pushing strings into an array, just remove the quotes so you're pushing objects, like this:

var data = [];
for (var i = 0; i < msg.d.ListExercise.length; i++) {
    data.push({ text: msg.d.ListExercise[i].exercise_value, id: msg.d.ListExercise[i].exercise_id });
}

Or since you tagged the question jQuery, use $.map() like this:

var data = $.map(msg.d.ListExercise, function() {
  return { text: this.exercise_value, id: this.exercise_id };
});
Nick Craver
@nick - I tried the $.map functionality and it returned nothing... Do I have to put that code inside the loop or is it supposed to loop through the data and add it to the array automatically?
Jeff V
@Jeff - ah crap I left a `.length` on there in the variable copy, the updated version should work, it'll replace all of the code in your question.
Nick Craver