homersheineken homersheineken - 6 months ago 24
JSON Question

Javascript push

I'm trying to push multiple values into an array.

When I use:

csvData.push('data[0][index],data[1][index],data[2][index],data[3][index]');


it formats it corrects so that

csvData[0] = "data[0][index],data[1][index],data[2][index],data[3][index]"
csvData[1] = "data[0][index],data[1][index],data[2][index],data[3][index]"
etc


Also when it evolves into a csv, it is correct in the 4 columns.

However when I use no quotes:

csvData.push(data[0][index],data[1][index],data[2][index],data[3][index]);


I get the values I want, but it's single dimensional.

csvData[0] = 23
92
74
22
etc


instead of

csvData[0] = 23,92,74,22


How can I add values it correctly?

Answer

You can create an array and push that:

csvData.push( [ data[0][index],data[1][index],data[2][index],data[3][index] ] ); 

The added brackets ([ ]) around the list of values creates an array, and that in turn is what's pushed onto the csvData array.