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:
File.readFile is a simple ES6 Promise wrapper around the node-native fs.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.
Likely not what you want, but the closest is probably
(x => ({ prop_a: x[0], prop_b: x[2], prop_c: x[1] }))(line.split('\t'));
But it is probably easiest to just do
var parts = line.split('\t');
return { prop_a: parts[0], prop_b: parts[2], prop_c: parts[1] };
While I might be proven wrong, I don't think what you want can be done by destructuring assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With