我正在閱讀一個帶有製表符分隔值的文件,我想將它轉換爲具有命名屬性的散列數組。語法爲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 *。解構是關於從集合中提取數據,而不是創建集合。對於那個使用對象或數組文字。 –