2016-03-22 23 views
1

我正在閱讀一個帶有製表符分隔值的文件,我想將它轉換爲具有命名屬性的散列數組。語法爲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的方法,我希望他們會發布。

+1

,你不能*用* destru構造一個對象cturing *。解構是關於從集合中提取數據,而不是創建集合。對於那個使用對象或數組文字。 –

回答

2

可能不是你所想要的,但最接近的可能是

(x => ({ prop_a: x[0], prop_b: x[2], prop_c: x[1] }))(line.split('\t')); 

但它可能比較容易只是做

var parts = line.split('\t'); 
return { prop_a: parts[0], prop_b: parts[2], prop_c: parts[1] }; 

雖然我可能會被證明是錯誤的,我不認爲有什麼你可以通過解構賦值來完成。

+0

我想我看到你在這裏:你定義了一個IIFE,它接受一個數組並返回該對象,並將拆分傳遞給IIFE。 Terse,但有效。 – Tom

0

這可能是另一個接近的:

var parts = line.split('\t'); 
var [name, species, age] = parts; 
return {name, species, age}; 
+0

對象字面值可以簡化爲'{name,species,age}'。 –

2

不能直接解構陣列成對象。無論如何,這沒有任何意義。

如果你有compose功能你可以做到這一點壽

let lines = x => x.split("\n"); 
let cells = x => x.split("\t"); 
let makeObject = ([name, species, age]) => ({name, species, age}); 

let data = "Ralphette\tdog\t7\nFelix\tcat\t5"; 
let result = lines(data).map(x => makeObject(cells(x))); 

console.log(result); 

輸出

[{"name":"Ralphette","species":"dog","age":"7"},{"name":"Felix","species":"cat","age":"5"}] 

,正如它的名字表明它變成只是有點清潔

const compose = (f,g) => x => f(g(x)); 

let result = lines(data).map(compose(makeObject,cells)); 

// result is the same 
相關問題