Reputation: 131
i have a question, i have a 'CSV file' data and it looks like this
source,xPos,target,xPos,value
user1,0,user2,1,4
user2,1,user3,2,4
user1,0,user3,2,2
user4,2
userA1,1,userA2,2,4
and I need to reform it, because my fuction uses a data set variable with in this format which is in somehow a JSON format and it should look like :
{
"nodes":[
{"node":0,"name":"user1","xPos":0},
{"node":1,"name":"user2","xPos":1},
{"node":2,"name":"user3","xPos":2},
{"node":3,"name":"user4","xPos":2},
{"node":4,"name":"userA1","xPos":1}
{"node":5,"name":"userA2","xPos":2}
],
"links":[
{"source":0,"target":1,"value":4},
{"source":1,"target":2,"value":4},
{"source":0,"target":2,"value":2},
{"source":4,"target":5,"value":4}]
}
and the sources and targets are the node numbers that they are already predefined.
Is it possible to do that in javascript ?
Upvotes: 1
Views: 112
Reputation: 744
First split the csv data by lines:
var lines = csvData.split("\n");
Then for each line split the line by comma (,)
var dataLine = lines[1].split(","); //not the 0th line as it has only the headers
Then loop dataLine
with for or forEach
and organize the data the way you want. Declare two json arrays one for "links"
and other for "nodes"
. Then assign your organized data to them.
And this is one of the way it is to be done.
Upvotes: 0