Javascript 数组的许多特定对象属性
我在我的express应用程序中使用sqlite3,当用户向我的系统添加新帐户时,我使用以下代码向数据库添加信息:Javascript 数组的许多特定对象属性,javascript,node.js,express,node-sqlite3,Javascript,Node.js,Express,Node Sqlite3,我在我的express应用程序中使用sqlite3,当用户向我的系统添加新帐户时,我使用以下代码向数据库添加信息: db.run(`INSERT INTO accounts(uuid, email, pass, device, user, pet, gold, is_active) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`, [this.uuid, this.email, this.pass, this.device, this.user, this.pet, th
db.run(`INSERT INTO accounts(uuid, email, pass, device, user, pet, gold, is_active) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`,
[this.uuid, this.email, this.pass, this.device, this.user, this.pet, this.gold, this.is_active],
function (err) {
if (err) {
return console.log(err.message);
}
});
db-是我的sqlite3实例
我相信应该有一种更好的编码方法(可能是一些带有spread的东西?)。
但我不知道如何只从“this”(它包含我数据库中不需要的其他属性)中获取特定属性。您可以创建一个属性数组,从
中提取该,然后.map
它:
const props = 'uuid email pass device user pet gold is_active'.split(' ');
db.run(
`INSERT INTO accounts(uuid, email, pass, device, user, pet, gold, is_active) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`,
props.map(prop => this[prop]),
function(err) {
if (err) {
return console.log(err.message);
}
}
);
通过保存属性字符串,您可以对其进行拆分并将其传递到的第一个参数,从而可以减少重复性(并且更不容易出错)。运行:
const propsStr = 'uuid, email, pass, device, user, pet, gold, is_active';
const props = propsStr.split(', ');
db.run(
`INSERT INTO accounts(${propsStr}) VALUES(${propsStr.replace(/\w+/g, '?')})`,
props.map(prop => this[prop]),
function(err) {
if (err) {
return console.log(err.message);
}
}
);
也许在第一个示例中添加props.join(‘,’)来添加它,就像INSERT-INTO-accounts(${props.join(‘,’)})值(?,,,,,,,,,,,,,,,?)
,也可以使用值(${Array(props.length)。填充(“?”).join(“,”)
,这样你就不必计算和键入所有的问号了。我也这么认为。非常感谢你们!