0

I'm kinda lost in figuring out the logic for javascript.

Currently, I'm extracting every element and pushing them into an array.

I'm having a hard time when I want to access the object element.

This is the data in the text file:

1#1#test#Tombstone#8#Yes
2#3#test2#Tombstone3#81#Yes

When I access the first array rowCells[0] . It returns me

1
2

which is the first column itself.

I was hoping for it to return the first row. The intended functionality is as follows:

1- Push everything to an array

2- Giving element key like first column is no,type,header,content,score

3- Search all the row based on the element key such as type=2

4- Search based on the type and no, then show the content.

Any suggestions? Thanks in advance.

<script type="text/javascript"
    src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

<script>
$.ajax({
  url: 'content.txt',
  dataType: 'text',
}).done(successFunction);


function successFunction(data) {
  var allRows = data.split(/\r?\n|\r/);
  var table = '<table>';
  for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
    var rowCells = allRows[singleRow].split('#');
    //table += rowCells.toString();

    table += '<br>';
    var first_word = rowCells;
    table += first_word;


  } 
  $('body').append(table);
}
</script>
2
  • why does a table have a br tag? Commented Jul 28, 2017 at 2:27
  • @epascarello to test the line content , it's redundant. Commented Jul 28, 2017 at 2:32

1 Answer 1

1

I would just use split, reduce, split, and join to build the table.

var str = `1#1#test#Tombstone#8#Yes
2#3#test2#Tombstone3#81#Yes`

var rows = str.split(/\n/g).reduce( function (str, row) {
  return str + "<tr><td>" + row.split(/#/g).join("</td><td>")  + "</td></tr>";
}, "")

var table = "<table><tbody>" + rows + "</tbody></table>"
$("#out").append(table)
td { border: 1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="out"></div>

Sign up to request clarification or add additional context in comments.

2 Comments

really appreciate for your answer, but let's say if i just want to show specific elements , like type = 3 . So ill need to push the elements to a key for me to match the criteria then only do it into a table.
so add an if statement when you generate it. var cells = row.split(/#/g); if (cells[0]=="2"){} else {}

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.