转换为键,值对

时间:2017-04-10 17:27:31

标签: javascript

我的问题

  1. 如何阅读JS中的rom txt文件
  2. 处理数据的最佳方法。下面这样的东西或????

    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"
    },
    

  3. 我希望有一个对象数组,以便我可以进一步处理它以打印出水果的独特名称,只是蔬菜和水果。

2 个答案:

答案 0 :(得分:1)

您可以使用AJAX然后使用正则表达式完成此操作。

如果你正在使用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);
    }
});

如果您不使用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();

答案 1 :(得分:0)

不要费心创建自己的解析器来阅读格式。

jsonxml

等标准数据交换格式保存您的内容

有许多其他人和查找标准库来解析它们并获取您的信息。

我会推荐使用json作为Javascript作为JSON对象来解析JSON文件。它们是解析JSON的其他好库。