I would like to save a two dimensional array consisting of one column of indicators (string) and one column of values (integer our double) in a file that has JSON format.
It somehow works but not the way I finally want it. I don't understand the problem why I get the result twice. Any idea around?
I am search the web for days and didn't find yet any answer that helped - or I didn't understand the answer. And yes it is client-side.
The function currently looks like this:
function array2JSON(fname) {
var totals = [
["ID_1", "ID_2", "ID_3", "ID_4", "ID_5","ID_6","ID_7","ID_8"],
[171.82, 54.0, 2.33, 1234.2, 1.23, 45.67, 0.98,0.123]
];
var totalsObj = totals.reduce((map, totals) => {
map.totals.push( {identifier: totals, values: totals});
return map;
}, { totals: []});
var myBlobFile = new Blob([JSON.stringify(totalsObj,null,4)], {
type: 'text/json;charset=utf-8'
});
var url = window.URL || window.webkitURL;
var temp_link = document.createElement('a');
temp_link.download = fname+".json";
temp_link.href = URL.createObjectURL(myBlobFile);
//temp_link.hidden = true;
// This link should not be displayed
document.body.appendChild(temp_link);
temp_link.click();
document.body.removeChild(temp_link);
}
What I get is this:
{ totals:
[ { identifier : [ 'ID_1', 'ID_2', 'ID_3', 'ID_4', 'ID_5', 'ID_6', 'ID_7', 'ID_8' ]
, values : [ 'ID_1', 'ID_2', 'ID_3', 'ID_4', 'ID_5', 'ID_6', 'ID_7', 'ID_8' ]
}
, { identifier : [ 171.82, 54, 2.33, 1234.2, 1.23, 45.67, 0.98, 0.123 ]
, values : [ 171.82, 54, 2.33, 1234.2, 1.23, 45.67, 0.98, 0.123 ]
} ] }
The problem is that you do not create the structure you want in your code with the reduce() function.
To get the output described by you in the comment there's no need to loop at all. You can just create a new object with the specified structure:
I am using array destructuring here. Instead of that you could also access the array by using indices.
If you want to ensure immutability (although you're not writing/ changing anything here) you can of course also copy the arrays e.g. by using the spread syntax like
[...identifiers](or usingidentifiers.slice()) and then reference the copies in your new object.