JavaScript将文件内容拆分为键值对
我有下面的UploadDocument事件,它有fileReader.result,它将下面的消息记录到控制台 控制台中的输出JavaScript将文件内容拆分为键值对,javascript,typescript,Javascript,Typescript,我有下面的UploadDocument事件,它有fileReader.result,它将下面的消息记录到控制台 控制台中的输出 A,B aa,dsf adfa,dfsd fdsafds,sdf uploadDocument(file) { let fileReader = new FileReader(); fileReader.onload =(e) => { console.log(fileReader.result); } fil
A,B
aa,dsf
adfa,dfsd
fdsafds,sdf
uploadDocument(file) {
let fileReader = new FileReader();
fileReader.onload =(e) => {
console.log(fileReader.result);
}
fileReader.readAsText(this.file);
如何使用javascript或Typescript将控制台中的上述内容(A、B…)拆分为键值对(如hashmap或Arraylist)
我试过把它分开
var lines=fileReader.result.split(/[\r\n]+/g);
控制台日志(行)
现在如何从中创建哈希映射?可以使用数组方法在每个元素上构建对象,因此我们只需将文件拆分为多行,然后将行数组缩减为一个对象
var map = fileReader.result.split('\n')
.reduce((obj, line) => {
var cols = line.split(',');
// Tolerate empty lines. There may be one at the end of the input.
if (cols.length >= 2) {
obj[cols[0]] = cols[1];
}
return obj;
}, {});
一种方法是使用它获取一个初始值(在本例中为一个新对象),并使用函数每次迭代时在逗号上拆分文件中每一行的结果填充其键和值
const input='A,B\n\
aa,dsf\n\
adfa,dfsd\n\
自卫队
const obj=input.split(/\n/g).reduce((p,c)=>{
常数s=c.split(',');
p[s[0]]=s[1];
返回p;
}, {});
console.log(obj)
Array.split
通过'\n'然后Array.reduce
(再次通过,
在回调内部拆分,)使用{}
作为累加器。如果lodash是一个选项,您可以在一个链中完成整个转换:.chain(fileReader.result).split('\n').map(line=>.split(line',')).fromPairs)().value()