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

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);

Related

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>

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

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]));

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
}
}

Getting top 10 Values in a JSON File [duplicate]

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
How to sort an array of objects with jquery or javascript [duplicate]
(6 answers)
Closed 8 years ago.
This is an example of my JSON file.
[
{"Variable":"Hello","Variable1":20}, {"Variable":"Hi","Variable1":30},
{"Variable":"How","Variable1":40}, {"Variable":"Who","Variable1":50},
{"Variable":"Where","Variable1":60}, {"Variable":"This","Variable1":100},
{"Variable":"Pork","Variable1":10}, {"Variable":"Creep","Variable1":90},
{"Variable":"Mega Creeps","Variable1":80}, {"Variable":"LOL","Variable1":0},
{"Variable":"ROFL","Variable1":0}, {"Variable":"LMAO","Variable1":0},
{"Variable":"POP","Variable1":0}, {"Variable":"LOVE","Variable1":0},
{"Variable":"PICK","Variable1":0}, {"Variable":"WHIZ","Variable1":0},
{"Variable":"BORED","Variable1":0}, {"Variable":"KILLAH","Variable1":0},
{"Variable":"LOLLING","Variable1":0}, {"Variable":"HALOO HALOO","Variable1":0}
]
How can I get only the Top 10 from highest Variable1 number to the least? But gonna be passing the JSON file as the same format.
First, parse the JSON into an array of Objects:
var data = JSON.parse(json);
Then combine sort and slice to achieve your goal:
var top10 = data.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
.slice(0, 10);
See Array.sort
You can do it with Alasql JavaScript library. It download json file, parse it, and run
SQL statement on it. This is a sample how to take top 10 directly from JSON file:
<script src="alasql.min.js></script>
<script>
alasql("SELECT TOP 10 * FROM JSON('mydata.json') ORDER BY Variable1 DESC",[], function(top10){
console.log(top10);
});
</script>
Or if you already have data in memory:
var data = [{"Variable":"Hello","Variable1":20},{"Variable":"Hi","Variable1":30}];
var res = alasql("SELECT TOP 10 * FROM ? ORDER BY Variable1 DESC",[data]);
Try this sample in jsFiddle.

How do I access CSV data using d3.js [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I have entered the following code in the Chrome console:
d3.csv("dataset32.txt")
.row(function(d) { return {time: +d.time, value: +d.val}; })
.get(function(error, rows) { console.log(rows); });
This returns an array of 160 objects which has the data of my CSV file.
How do I reference the data in these objects?
The "dataset32.txt" is CSV data which looks like this:
time,val
0,1.8988762857143
0.0625,0
0.125,-2.6204492857143
0.1875,-0.34179771428571
The console prints out the result of the above commands as follows:
[Object, Object, Object…]
[0 … 99]
0: Object
time: 0
value: 1.8988762857143
__proto__: Object
So how do I reference the data inside these objects: "time" and "value"?
Here's a straight forward method for importing your csv file using d3.
d3.csv("path to the csv", function(data, error) { }).
More info about csv.
Here's a function that's help you.
Step 1 : Importing your CSV file.
d3.csv("path to your csv file", function(data, error) {
// You're function goes in here.
})
Step 2 : Targeting your data.
// This can be done using the data variable assigned in the function.
data.forEach(function(d) {
// Function goes in here.
})
Step 3 : Targeting your columns.
// Suppose you have 2 columns namely time and val.
data.forEach(function(d) {
// You can target your columns using this fucntion.
// function(d) {return d.colname}
// Here I'm parsing your time and val col numbers to actual numbers after importing.
d.time = +d.time;
d.val = +d.val;
})
Documentation for d3.
Hope this helps.

Categories

Resources