根据格式将纯文本数据转换为带有数组的对象



转换纯文本数据的最佳方法是:

[group a]
a
b
c
[group b]
a
d
f

变成一个对象…

{
groupA: ['a', 'b', 'c'],
groupB: ['a', 'd', 'f']
}

纯文本数据的长度各不相同,但其结构总是这样表示的:

[parent group]
child item 1
child item 2
...

(1)从split()开始,以[作为分隔符,它应该为您提供字符串中尽可能多的组:

[ '', 'group a]nanbncn', 'group b]nandnf' ]

(2)使用.filter()去除不需要的空字符串:

[ 'group a]nanbncn', 'group b]nandnf' ]

(3)现在使用.map()变换每组,使用]n作为分隔符:

[ [ 'group a', '', 'a', 'b', 'c', '' ], [ 'group b', '', 'a', 'd', 'f' ] ]

(4)使用.filter()删除不需要的空字符串:

[ [ 'group a', 'a', 'b', 'c' ], [ 'group b', 'a', 'd', 'f' ] ]

(5)最后使用.reduce()Object.assign()将每个组转换成一个键值对:

{ 'group a': [ 'a', 'b', 'c' ], 'group b': [ 'a', 'd', 'f' ] }

请注意那个片段,

.split(' ').map((a,i) => i === 0 ? a : a.toUpperCase()).join('')

是将group a转换为groupA,等等

let data = `[group a]
a
b
c
[group b]
a
d
f
[group c]
g
h
t`;
let obj = data
.split(/[/)
.filter(v => v) 
.map(v => v.split(/]|[rn]+/)
.filter(v => v))
.reduce((acc,val) => 
Object.assign(acc,
{[val[0].split(' ').map((a,i) => i === 0 ? a : a.toUpperCase()).join('')]:val.slice(1)}),{});
console.log( obj );

您可以使用分割和减少

const string = `[group a]
a
b
c
[group b]
a
d
f`
const list = string.split(`n`)
let saveKey;
const obj = list.reduce((acc,cur) => {
if (cur.startsWith('[')) { 
const groupLetter = cur.match(/ (w+)]/)[1].toUpperCase()
saveKey = `group${groupLetter}`;
acc[saveKey]=[];
}  
else {
acc[saveKey].push(cur);
}  
return acc
},{})
console.log(obj)

您可以抓取所有文本行,并通过解析和确定它是键还是值来减少行数。累加器需要存储结果和当前键。

const
parse = (text) =>
text.trim().split('n')
.reduce((acc, line) => {
const match = line.trim().match(/^[(.+)]$/);
return match
? { ...acc, key: match[1] }
: { ...acc, result: { ...acc.result,
[acc.key]: [...(acc.result[acc.key] ?? []), line.trim()] }
};
}, { result: {}, key: null }).result,
data = parse(document.querySelector('#data').value);
console.log(data);
.as-console-wrapper { top: 0; max-height: 100% !important; }
#data { display: none; }
<textarea id="data">[group a]
a
b
c
[group b]
a
d
f</textarea>

通过在n上分割原始字符串创建一个数组,然后循环并创建对象:

const str = `[group a]
a
b
c
[group b]
a
d
f`
const arr = str.split('n')
const obj = {}
let curHeader
arr.forEach(el =>
{
if(el[0] === '[')
{
let frmtEl = el.substring(1, el.length-1)
let frmtElArr = frmtEl.split(' ')
curHeader = frmtElArr[0] + frmtElArr[1].toUpperCase()
obj[curHeader] = []
}
else
{
obj[curHeader].push(el)
}
})
console.log(obj)