Javascript: How to save csv data from XMLHTTPRequest in an Array [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I tried to get some Data from a csv file with the following code:
(The csv file are several lines which are different rows from a table)
var newArray = []
function init() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var lines = this.responseText.split("\n");
newArray.push(lines)
}
}
xhttp.open("GET", "CMDBsox.csv", true);
xhttp.send();
}
window.onload = init;
console.log(array)
The csv file looks like this:
(I just noticed that the first element of each line is not in quotes " )
First line: Lorem1, "Lorem2", "Lorem3", "Lorem4",...
Second line: Ipsum1, "Ipsum2", "Ipsum3", "Ipsum4",...
and so on
I pushed the 'lines' array into a new array called newArray.
Now I can see the array but all rows are in another array like:
0:(21) [...]
0:["Sample1", "Sample2", "Sample3,...]
1:["Example1", "Example2", Example3",...]
2:["Test1", "Test2", "Test3",...]
and so on...(21 times)
I can access the different arrays(rows) with:
"newArray[0][0]", "newArray[0][1]", "newArray[0][2]",...
but now I have trhee problems:
I can acces them via console but not via code...
when I write newArray[0][1] I get the error **"TypeError: array[0] is undefined"**.
But in the console I can see the whole array?
How can I create new arrays inside the array. For example, now I have a big string inside newArray[0][0] but I need the single elements in an array
I currently access every "line" via newArray[0][i] but I want to access them with newArray[i].. how can I move them into the "upper" array so I don't have that useless first array
Thank You :)

I do not understand why you are diverting your question on the problem of reading a file while it is only a problem on the copy of a table in another.
Asking clear questions is essential if you expect good answers.
so push a array inside a array is bad idea, use Object.assign
var arr1 = [ 1,7 ,3 ,4 ,5];
var arr2 = [[]];
Object.assign (arr2[0], arr1)
console.log ('arr1 ...: ', JSON.stringify(arr1));
console.log ('arr2[0] : ', JSON.stringify(arr2[0]));

Related

Attempting to compare a standalone variable to each value in an array

I am writing a script to use on a Google Sheet where I am accepting user input and comparing it to the values already present on the spreadsheet.
In the function below I have retrieved the users desired number with the variable voltReqed.
I am attempting to compare it (detect less than or greater than) to each value in the array generated with the variable voltCompareData.
I am quite new to scripts, please excuse my ignorance.
function getVoltage() {
var voltReqed = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange("A1").getValue();
Logger.log(voltReqed);
var voltCompareData = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SpecsList").getSheetValues(3, 2, 1, 3);
Logger.log(voltCompareData);
var voltSample1 = voltCompareData.getValue(1,1);
Logger.log(voltSample1);
}
The variable voltSample1 was me attempting to pull the first number out of the array generated by the voltCompareData variable for comparison operations.
Please see the image for the number and array retrieved and logged by the above script.
Comparing data to variable
function getVoltage() {
var voltReqed = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getRange("A1").getValue();
var vs = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SpecsList").getSheetValues(3, 2, 1, 3).flat();
vs.forEach(e => {
if(e == v) {
//do someting
}
});
}

How to make the Select option appending with html? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed last year.
Am making an select option from ajax success. The problem is that, the results are array so i need to manipulate the array with some html.
My appending code:
data = [['2022-02-01', '2022-02-02'],['2022-03-01', '2022-03-02'],['2022-04-01', '2022-04-02']]
$("#id_course").change(function () {
$('select[id=id_intakes]').empty().prepend("<option></option>");
$.each(data, function(index, date){
$('select[id=id_intakes]').append(
$('<option></option>').attr("value",date).text(date)
)
});
})
Just creates the select correctly, but it displays the array as it is. The dropdown contains all the three values array
['2022-02-01', '2022-02-02']
['2022-03-01', '2022-03-02']
['2022-04-01', '2022-04-02']
I need to manipulate this like
From:2022-02-01 & To:2022-02-02
From:2022-03-01 & To:2022-03-02
From:2022-04-01 & To:2022-04-02
So how to do this ?
You can add this to your code:
name = `From:${name[0]} & To:${name[1]}`;
Demo
data = [
['2022-02-01', '2022-02-02'],
['2022-03-01', '2022-03-02'],
['2022-04-01', '2022-04-02']
]
$('select#id_intakes').empty().prepend("<option></option>");
$.each(data, function(index, name) {
name = `From:${name[0]} & To:${name[1]}`;
$('select[id=id_intakes]').append(
$('<option></option>').attr("value", name).text(name)
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="id_intakes"></select>

Merge two arrays of arrays by ID in AppsScript

I have two arrays in an App Script project, one with a user email and their last login date, and one with their email and license type. I'd like to combine these two arrays into an array where each item has their email, last login, and license.
It's not guaranteed that the arrays will be in the same order.
Example:
Array 1: [[google.user#domain.com, Google-Apps, 1010020020],[google.user2#domain.com, Google-Apps, 1010020020]
Array 2: [[google.user2#domain.com, 12/31/1969],[google.user#domain.com, 12/31/1969]]
becomes
Array 3: [[google.user#domain.com, 12/31/1969, Google-Apps, 1010020020],[google.user2#domain.com, 12/31/1969, Google-Apps, 1010020020]]
I tried several of the methods described in this post and this post but they seem to be ES6 and throw errors when I run them.
In es5, your code should be like this:
var a1 = [['google.user#domain.com', 'Google-Apps', '1010020020'],['google.user2#domain.com', 'Google-Apps', '1010020020']]
var a2 =[['google.user#domain.com', '12/31/1969'],['google.user2#domain.com', '12/31/1969
var a3 = new Array()
for(var i=0;i<a1.length;i++){
a3[i]=new Array();
a3[i][0]=a1[i][0];
a3[i][2]=a1[i][1];
a3[i][3]=a1[i][2];
}
for(var i=0;i<a2.length;i++){
for(var j=0;i<a3.length;j++){
if(a3[j][0] == a2[i][0]){
a3[j][1] = a2[i][1];
break;
}
}
}

How to get D3 csv data into a different variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to extract imdb data from a csv and put two elements of it into an array of objects. There are 10 fields. I only want to use 2 in my chart. I am trying this:
var mydata;
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata += {rating: d.imdbRating,
winsNoms: d.WinsNoms };
});
});
console.log(mydata);
Can somebody explain exactly what is going on here and why I get undefined when I try to output mydata in the final line? Finally, how do I change it around so it works?
You should push objects into an array. See adjustments below:
var mydata = [];
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata.push({
rating: d.imdbRating,
winsNoms: d.WinsNoms
});
});
});
console.log(mydata);
You’ll need to first declare an empty array. Then you can push items into it.
To only use part of the set, you can use “slice” to truncate the array.
var mydata = [];
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata.push({rating: d.imdbRating,
winsNoms: d.WinsNoms });
});
});
console.log(mydata);

Read a JSON list in list [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have a json like this :
{
"Project
[id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd ]"
:
[
{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
{"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
]
}
originated from : return new ObjectMapper.write(Map<Project,List<Task>> projectTasks = new LinkedMultiValueMap<>()) ;
EDIT : this is the real response :
{"Project [id=1, name=qsdsqd, type=null, done=false, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, client=qsd, showable=true]":
[{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"},
{"id":2,"title":"task 2 ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"}]}
How can I read the list of tasks in the client side ?
First of all, your JSON is not valid. Are you sure that is a line break between the word Project and [id...]. A valid JSON would be:
{
"Project [id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, ]":
[
{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
{"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
]
}
You can have object key names like that. But i'ts not very friendly to retrieve data.
If you cannot change your data schema (or just don't want), you can iterate over the Object with the
Object.keys(obj).forEach ( (key) => {
console.log('key: ' + key);
console.log('value: ' + obj[key]);
/* you can iterate over your value (tasks) here */
obj[key].forEach( (task) => {
console.log('task1: ', task);
});
}); //where obj is your json
Or you can access the first object property with:
obj[Object.keys(obj)[0]]; //where obj is your json
EDIT As pointed by #André Dion, forEachis best suited to iteration, not map. And we're assuming your response is already parsed from the server (by yourself or by a lib like jquery). If not, you should do a JSON.parse(response); to retrieve the object.
You may try this:
Assume above response in stored in var response.
for(var project in response) { // this will get every project
for(var i=0; i<project.length; i++) { // this will iterate over the array for each project which are your tasks.
console.log("task" + project[i]);
console.log(project[i]["id"]); // access each tasks id, similar for other attributes
}
}

Categories

Resources