I have an ajax call that returns a 2D object and I want to be able to convert it into a .csv
file for the user to download.
The php code: echo json_encode($results);
The js function, right now has console.log (JSON.parse(res));
so I can verify the contents.
The console log shows:
Object {color: Object, animal: Object}
color: Object
1: "red"
2: "white"
3: "blue"
animal: Object
1: "cat"
2: "dog"
3: "mouse
Each of the inner objects always has the same number of elements (in this case, 3)
I would like to convert this to a csv and then download. The first line of the csv would contain the outer object keys (color, animal) The csv would end up like this:
"color, animal"
"red, cat"
"white, dog"
"blue, mouse"
With the solutions I've looked at, they append a joined version of the object to each row. I need to transpose the data vertically.
I think that I need to step through each inner object (get the nth element of each one, get the n+1th element of each one etc) and build my own csv strings, but that seems awfully clunky.
Any nifty array/object functions out there that can help me?
I am able to create and download a .csv file, it's just this data transpose logic that has me stuck.
EDIT: I am not trying to convert a csv string to an array, nor am I trying to transpose a 2D array (it's a 2D object).
Clarification In my ajax call to the php file, I am sending an array of ["color", "animal"]
which is derived from user input. The php file reads this array and gathers data based on this array. Once the data has been gathered, it returns a 2D array, the inner array being the new data. Thus:
[color[red, white, blue], animal[cat,dog,mouse]]