I’m parsing a document that has a known repeating structure. There is a heading (1 line), a sub-heading(1 line), and a content area (unknown # of lines).
The format for each item in the document is shown below:
=========================
Head Text
=========================
SubHead Text
=========================
Content Text Line 1
Content Text Line 2
...
Content Text Line 8
I want to create an Array that contains an Object for each section.
Something like:
var item = [];
items[0] = {
head: "head1 text",
subHead: "subHead1 text",
content: "content1 text"};
items[1] = {
head: "head2 text",
subHead: "subHead2 text",
content: "content2 text"};
I am having trouble efficiently traversing the document and dynamically adding each Object into the Array. I get an error under section 2 telling me that “page is null or not an object”.
var count = 0;
while( !stream.AtEndOfStream ){
page[count] = stream.ReadLine();
count++;
}
var item = [{}];
var section = 0;
var i = 0, k = 0;
while (i < page.length) {
if (~page[i].indexOf("=====")) {
if(section == 0) {
item[k].head = page[i+1];
section++;
} else
if (section == 1) {
item[k].subHead1 = page[i+1];
section++;
i++;
} else
if (section == 2) {
var j = i+1;
while(!~page[j].indexOf("=====")) {
item[k].content += page[j] + "\n";
j++;
}
section = 0;
k++;
}
}
i++;
}
Change this:
to this:
Next, change this:
to this:
I am not sure if that will work, but the basic idea is to create a blank array (var item = [];) and then add objects when needed (item[k] = {}). Previously you were trying to add properties to undefined objects.