簡體   English   中英

es6從數組解構為對象的語法

[英]syntax for es6 destructuring from an array into an object

我正在讀取帶有制表符分隔值的文件,我想將其轉換為具有命名屬性的哈希數組。

我已經研究了關於Destructuring assign的MDN頁面 ,但是一些更復雜的例子對我沒有意義,我沒有看到導致單個對象的語法。

這是我到目前為止所得到的:

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的babel。 如果需要,我願意加載額外的解析或轉換插件。
  • File.readFile是一個圍繞node-native 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' }
]

謝謝你的幫助!


回答

聽起來似乎沒有辦法只通過解構來做到這一點。 然而,在混合物中引入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的方法,我希望他們會發布它。

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

(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] };

雖然我可能被證明是錯的,但我不認為你想要的是通過解構分配來完成的。

您無法將數組直接解構為對象

這個答案采用分解的方法,而不是將所有內容捆綁在一個大的混亂功能中。 這里的各個功能更易於編寫,維護和測試。 執行單個任務的小功能也更容易在程序的其他部分重用。

 const lines = x => x.split("\\n") const cells = x => x.split("\\t") const makeObject = ([name, species, age]) => ({name, species, age}) const data = "Ralphette\\tdog\\t7\\nFelix\\tcat\\t5" const result = lines(data).map(x => makeObject(cells(x))) console.log(result) // [ { name: "Ralphette", species: "dog", age: "7" } // , { name: "Felix", species: "cat", age: "5" } // ] 


如果你有一個compose功能,它會變得更加清晰

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

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

console.log(result)
// [ { name: "Ralphette", species: "dog", age: "7" }
// , { name: "Felix", species: "cat", age: "5" }
// ]

如果,從現在起,有人發現沒有IIFE的方法,我希望他們會發布它。

已經有幾年了,所以這里是你的答案的編輯,不涉及立即調用的功能 -

File
  .readFile(filepath, 'utf8')
  .then
    ( fileContents => 
        fileContents.length === 0
          ? []
          : fileContents
              .split('\n')
              .map(line => line.split('\t'))
              .map(([ name, species, age ]) => ({ name, species, age }))
    )

這實際上與我上面的原始答案做了同樣的事情,只是效率較低,因為它使用兩個調用來map 以下是將linescellsmakeObject連接到原始代碼的方法 -

File
  .readfile(filepath, 'utf8')
  .then
    ( fileContents => 
        fileContents.length === 0
          ? []
          : lines(fileContents).map(line => makeObject(cells(line))
    )

還有一件事 ...

File.readFile是一個圍繞node-native fs.readFile (path,opt,callback)API的簡單ES6 Promise包裝器

Node現在為fs模塊提供了基於Promise的API 您可以簡單地 - 而不是定義自己的包裝器 -

const { readFile } = require("fs").promises

readFile(filePath, 'utf8').then(results => ...)

這可能是另一個最接近的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM