I am trying to write a tool that takes a CSV and dynamically generates a definition based on the header row?
For example, a CSV with:
Title(STRING), Description(TEXT)
Title Example, Description Example
...
the Sequelize docs specify, for example:
var Entry = sequelize.define('Entry', {
title: Sequelize.STRING,
description: Sequelize.TEXT
})
How could I write this definition so that it could be dynamically defined - so that title
and the data type Sequelize.STRING
could be dynamically generated based on the CSV header row?
EDIT
Ok, after some research, I think the obvious question is "How to use variable names as dynamic key names in object literal" and has been answered several times.
As a result, it is simple to write this in bracket notation so:
var definitionObj = {}
definitionObj['title'] = sequelize.STRING;
definitionObj['description'] = sequelize.TEXT;
var Entry = sequelize.define('Entry', definitionObj);
However, then my question now is how do I use ES6 Computed Property Names in node ? I'm using node 0.12.2 which I thought had ES6 support, and even with the --harmony
flag, this simple code fails:
var Entry = sequelize.define('Entry', {
['title']: Sequelize.STRING,
['description']: Sequelize.TEXT
});
with SyntaxError: Unexpected token [
Is the only option really to go to with io.js ?
EDIT 2
Actually this syntax still fails even with iojs, so I must be doing something wrong?
In current Node release > 4.x you have some support for ES6. Status can be found in documentation: https://nodejs.org/en/docs/es6/
What you are looking for is called
Computed (dynamic) property names
and it is fully supported now. Details can be found here: https://github.com/lukehoban/es6features#enhanced-object-literals
Usage:
var obj = {
// Computed (dynamic) property names
[ 'prop_' + (() => 42)() ]: 42
};
Will produce object: {prop_42: 42}
The ECMAScript 6 compatibility table shows that neither Node nor io.js currently have support for computed properties. The data is under object literal extensions > computed properties .
Now can use it in iojs v3.0
Changelog https://github.com/nodejs/io.js/blob/master/CHANGELOG.md#user-content-notable-changes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.