许多特定的对象属性数组

Many specific object properties to array

我在我的 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, this.gold, this.is_active],
    function (err) {
        if (err) {
            return console.log(err.message);
        }
    });

db - 是我的 sqlite3 实例

我相信应该有更好的编码方式(也许有传播的东西?)。 但我不明白如何只从 'this' 获取特定属性(它包含我的数据库中不需要的其他属性)

您可以创建一个属性数组以从 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);
    }
  }
);

可以通过保存属性字符串来减少重复(并且更不容易出错),这样你就可以拆分它 传递给 [=14 的第一个参数=]:

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);
    }
  }
);