I'm reading a file with tab-separated values, and I'd like to transform it into an array of hashes with named properties.
I've studied the MDN page on Destructuring assignment, but some of the more involved examples don't make sense to me, and I don't see a syntax that results in a single object.
Here's what I've got so far:
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');
}));
A couple things to note:
- I'm using babel with node v5. I'm willing to load additional parsing or transform plugins if necessary.
File.readFileis a simple ES6 Promise wrapper around the node-nativefs.readFile(path, opt, callback)API.
I'm looking for a single statement that can split line and arbitrarily assign from that into a newly created object. I assume destructuring is the right way to pull this off, but perhaps what's needed is e.g. some inventive use of rest or spread.
// sample input text
Ralphette dog 7
Felix cat 5
// desired output
[ { name: 'Ralphette', species: 'dog', age: '7' },
{ name: 'Felix' , species: 'cat', age: '5' }
]
Thanks for your help!
ANSWER
It sounds like there's no way to do this with destructuring only. However, introducing an IIFE into the mix makes for a one-liner with less-exotic destructuring. Here's the code I used, based on @Amadan's answer:
return File.readFile(filepath, 'utf8')
.then((fileContents) => (fileContents.length === 0)
? []
: fileContents
.split('\n')
.map((line) => (([ name, species, age ]) => ({ name, species, age }))(line.split('\t')))
)
It's quite terse, and for that reason I'd advise against using it in a real project.
If, years from now, someone discovers a way to do this without the IIFE, I hope they will post it.