0

My question

  1. How to read rom txt file in JS
  2. Best approach to process the data. Something like this below or ????

    var data = [
    {
      name: "Orange",
      type: "Fruit",
      desc: "some description about the recipe"
    },
      {
      name: "Spinach",
      type: "Veg",
      desc: "some description about the recipe"
    },
      {
      name: "Beans",
      type: "Veg",
      desc: "some description about the recipe"
    },
    

    ]

I want to have an object array so that I can process it further to print out unique names of fruits, just veggies and just fruits.

early_ninja
  • 109
  • 1
  • 2
  • 9

2 Answers2

1

You can accomplish this using AJAX and then a regular expression.

If you're using jQuery:

$.ajax({
    url: 'someTextFile.txt',
    success: function(data) {
        var regEx = /([a-zA-Z]+), ([a-zA-Z]+).*[\r\n  \t]*([a-zA-Z0-9 \.]+)/g,
            recipe, allRecipies = [];
        while (recipe = rege.exec(data)) {
            allRecipies.push({
                name: recipe[1],
                type: recipe[2],
                desc: recipe[3],
            });
        }
        console.log(allRecipies);
    }
});

If you're not using jQuery

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       data = xhttp.responseText;
        var regEx = /([a-zA-Z]+), ([a-zA-Z]+).*[\r\n  \t]*([a-zA-Z0-9 \.]+)/g,
            recipe, allRecipies = [];
        while (recipe = rege.exec(data)) {
            allRecipies.push({
                name: recipe[1],
                type: recipe[2],
                desc: recipe[3],
            });
        }
        console.log(allRecipies);
    }
};
xhttp.open("GET", "filename", true);
xhttp.send();
HoofHarted
  • 176
  • 2
  • 5
0

Don't bother creating your own parser to read in formats.

Save your content in a standard data-interchange format like json or xml

There are so many others and lookup standard libraries to parse them and get your information.

I'll recommend json, as Javascript as a JSON object for parsing JSON Files. And their are other good libraries for parsing JSON.

Subomi
  • 380
  • 1
  • 2
  • 14