【问题标题】:JS: Convert text into object arrayJS:将文本转换为对象数组
【发布时间】:2016-03-06 08:44:36
【问题描述】:

我需要转换这个...

# 4.0.0 - 2016-01-01
- some text without category

# 3.12.0 - 2016-02-01
- Category: some text

# 3.11.4 - 2016-03-01
- Category: some multiple text
- Something: some text
- Anything: more text

...进入(对象)数组。我不知道如何让所有元素都连接到它的版本。

结果应该是这样的(最后一个块的例子)

[
    { 
        major: 3,
        minor: 11,
        patch = 4,
        date = '2016-03-01',
        entries = [
            { category: 'Category', 'some multiple text' },
            { category: 'Something', 'some text' },
            { category: 'Anything', 'more text' }
        ]
    }
]

正如您在第一块中所见,entries 中的字段 category 是可选的。

这就是我尝试的方式:

var lines = text.split('\n');
for(var i = 0;i < lines.length;i++){
    var meta = lines[i].split(' ');
    var version = meta[1].split('.');
    result['major'] = version[0];
    result['minor'] = version[1];
    result['patch'] = version[2];
    result['date'] = meta[3]
}

但这仅适用于每个块的第一行。

【问题讨论】:

  • 必须在JavaScript 中吗?其他引擎(例如 PHP 中的 PCRE)提供了更好的功能,例如 \G
  • 是的,必须是JS。

标签: javascript arrays regex split


【解决方案1】:

此提议将字符串拆分为块并测试块是否为#-。这些行被评估并添加到结果中。

var text = '# 4.0.0 - 2016-01-01\n- some text without category\n- Just a text: with double point\n\n# 3.12.0 - 2016-02-01\n- Category: some text\n\n# 3.11.4 - 2016-03-01\n- Category: some multiple text\n- Something: some text\n- Anything: more text',
    result = function (text) {
        var array = text.split('\n'),
            o, r = [];
        array.forEach(function (a) {
            var p, v;
            if (a[0] === '#') {
                o = {};
                p = a.match(/^# ((.*) - )?(.*)$/);
                v = p[2].split('.');
                o.major = v[0];
                o.minor = v[1];
                o.patch = v[2];
                o.date = p[3];
                r.push(o);
            }
            if (a[0] === '-') {
                if (!o.entries) {
                    o.entries = [];
                }
                p = a.match(/^- ((\w*): )?(.*)$/);
                o.entries.push({ category: p[2], value: p[3] });
            }
        });
        return r;
    }(text);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

【讨论】:

  • 只有一件事:只有当它是一个单词时才应该提取类别。示例:Category: Some Text 会给我一个类别字段。但是Just a text: with double point 没有给我分类字段,只给了值字段。
  • @user3142695,请查看编辑,使用已编辑的正则表达式:/^- ((\w*): )?(.*)$/ 进行纯单词搜索。
【解决方案2】:

这可以通过为不同类型的行和一些正则表达式编写不同的函数来解决:

var text = `# 4.0.0 - 2016-01-01
- some text without category

# 3.12.0 - 2016-02-01
- Category: some text

# 3.11.4 - 2016-03-01
- Category: some multiple text
- Something: some text
- Anything: more text`;

var lines = text.split('\n');
var all = [];
for(var i = 0;i < lines.length;i++){
  var firstChar = lines[i].substr(0, 1);
  if (firstChar === '#'){
    all.push(extractVersionInfo(lines[i]));
  }
  else if (firstChar === "-"){
    all[all.length-1].entries.push(extractNote(lines[i]));
  }
}
console.log(all);

function extractNote(text){
  var withoutDash = text.substr(2);
  if (withoutDash.indexOf(":") !== -1){
    var parts = withoutDash.split(":");
    return {category: parts[0],
        value: parts[1]
       };
  }
  else {
    return {value: withoutDash};
  }
}

function extractVersionInfo(text){
  var pattern = /# ([0-9]+)\.([0-9]+)\.([0-9]+) - ([0-9]{4}-[0-9]{2}-[0-9]{2})/;
  var match = text.match(pattern);
  result = {};
  result.major = match[1];
  result.minor = match[2];
  result.patch = match[3];
  result.date = match[4];
  result.entries = [];
  return result;
}

输出:

[ { major: '4',
    minor: '0',
    patch: '0',
    date: '2016-01-01',
    entries: [ { value: 'some text without category' } ] },
  { major: '3',
    minor: '12',
    patch: '0',
    date: '2016-02-01',
    entries: [ { category: 'Category', value: ' some text' } ] },
  { major: '3',
    minor: '11',
    patch: '4',
    date: '2016-03-01',
    entries: 
     [ { category: 'Category', value: ' some multiple text' },
       { category: 'Something', value: ' some text' },
       { category: 'Anything', value: ' more text' } ] } ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 2012-05-07
    • 2018-02-06
    相关资源
    最近更新 更多