0

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?

1 Answer 1

2

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 !
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.