我需要转换这个...
# 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
...进入(对象)数组。我不知道如何使所有元素与其版本保持连接。
结果应该如下所示(最后一个 block 的示例)
[
{
major: 3,
minor: 11,
patch = 4,
date = '2016-03-01',
entries = [
{ category: 'Category', 'some multiple text' },
{ category: 'Something', 'some text' },
{ category: 'Anything', 'more text' }
]
}
]
正如您在第一个 block 中看到的,在 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]
}
但这仅适用于每个 block 的第一行。
最佳答案
该提案将字符串拆分为 block 并测试 block 的 #
或 -
。这些行将被评估并添加到结果中。
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>');
关于javascript - JS : Convert text into object array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35824834/