我正在阅读一个带有制表符分隔值的文件,我想将它转换为具有命名属性的散列数组。语法为es6解构从一个数组到一个对象
我研究了the MDN page on Destructuring assignment,但一些更多涉及的例子对我来说没有意义,而且我没有看到导致单个对象的语法。
这里是我到目前为止有:
return File.readFile(filepath, 'utf8')
.then((fileContents) => fileContents.split('\n').map((line) => {
// here is where I'd convert the line of tab-separated
// text into an object with named properties
// this is fake, broken syntax
return ({ prop_a: [0], prop_b: [2], prop_c: [1] }) = line.split('\t');
}));
几件事情要注意:
- 我用巴贝尔与节点V5。如果需要,我愿意加载额外的解析或转换插件。
File.readFile
是围绕节点本机fs.readFile(path, opt, callback)
API的简单ES6 Promise包装。
我正在寻找一个单独的声明,可以拆分line
并任意分配到一个新创建的对象。我认为解构是解决这个问题的正确方法,但也许需要的是休息或传播的一些创造性用途。
// sample input text
Ralphette dog 7
Felix cat 5
// desired output
[ { name: 'Ralphette', species: 'dog', age: '7' },
{ name: 'Felix' , species: 'cat', age: '5' }
]
感谢您的帮助!
ANSWER
听起来好像也没有办法,只有解构做到这一点。然而,将IIFE引入混合使得这种单线程解决方案具有不那么奇特的解构。下面是我使用的代码的基础上,@ Amadan的回答是:
return File.readFile(filepath, 'utf8')
.then((fileContents) => (fileContents.length === 0)
? []
: fileContents
.split('\n')
.map((line) => (([ name, species, age ]) => ({ name, species, age }))(line.split('\t')))
)
这是相当简洁,因为这个原因,我建议不要在一个真正的项目中使用它。
如果从现在开始,有人发现了一种没有IIFE的方法,我希望他们会发布。
,你不能*用* destru构造一个对象cturing *。解构是关于从集合中提取数据,而不是创建集合。对于那个使用对象或数组文字。 –