Reputation: 23
I am new to javaScript, suppose I have a text file (test.txt) contains hundreds of lines of code and have the following format:
4 6
5 7
4 7
2 6
...
The first num in each line is source and second num is target. Right now I want to parse into the javaScript objects like this:
var links = [
{source: '4', target: '6'},
{source: '5', target: '7'},
{source: '4', target: '7'},
{source: '2', target: '6'}];
How can I do that?
Upvotes: 0
Views: 1432
Reputation: 1191
I'm going to assume here that you already have the contents of your file in a string named filecontent
(doing that is already a nontrivial thing, depending on where your javascript resides). Then here is a straight-forward implementation :
var lines = filecontent.split('\n');//puts the lines in an array
var links = [];
for(var i = 0; i < lines.length; ++i){
var values = lines[i].split(' ');//transforms "4 6" into ["4", "6"]
links[i] = {source : values[0], target : values[1]};
//then into the format you wanted !
}
Upvotes: 2