在JavaScript键值对象中,如何从值中删除引号



从远程db中,我检索表格的架构,并获取以下表单的json对象:

{ Id:                 
   { type: 'INT',          
     allowNull: false,     
     defaultValue: null,   
     primaryKey: false },  
  Prefix:                    
   { type: 'NVARCHAR',     
     allowNull: true,      
     defaultValue: null,   
     primaryKey: false },  
  FirstName:               
   { type: 'NVARCHAR',     
     allowNull: true,      
     defaultValue: null,   
     primaryKey: false },  
  Assets:               
   { type: 'INT',          
     allowNull: false,     
     defaultValue: null,   
     primaryKey: false },  
  Role:          
   { type: 'NVARCHAR',     
     allowNull: true,      
     defaultValue: null,   
     primaryKey: false },  
}

我想将每个列的type转换为 DataTypes.INTEGERDataTypes.STRING中的某些内容(id,prefix,firstName,资产,角色(,因此我们得到:

 { Id:                 
   { type: DataTypes.INTEGER,          
     allowNull: false,     
     defaultValue: null,   
     primaryKey: false },  
  Prefix:                    
   { type: DataTypes.STRING,     
     allowNull: true,      
     defaultValue: null,   
     primaryKey: false },  
  FirstName:               
   { type: DataTypes.STRING,     
     allowNull: true,      
     defaultValue: null,   
     primaryKey: false },  
  Assets:               
   { type: DataTypes.INTEGER,          
     allowNull: false,     
     defaultValue: null,   
     primaryKey: false },  
  Role:          
   { type: DataTypes.STRING,     
     allowNull: true,      
     defaultValue: null,   
     primaryKey: false },  
}

请注意差异,type值不再是字符串。

最初我正在尝试以下操作:

var DataTypes = {
    NVARCHAR: 'STRING',
    INT: 'INTEGER',
    VARCHAR: 'STRING',
    DATETIME: 'DATE',
    FLOAT: 'FLOAT',
    NCHAR: 'STRING'
}
Object.keys(schema).forEach(function(fieldName) {
        types[schema[fieldName]['type']] ? schema[fieldName]['type'] = 'DataTypes.'+types[schema[fieldName]['type']] : console.log('Could not find type: ' + schema[fieldName]['type'])
    })

,但是我会得到"DataTypes.STRING"而不是DataTypes.STRING

我从未使用过您在评论中提到的链接,但是快速查看他们的文档表明这是您定义新模型的方式:

const WhateverYouWant = sequelize.define('whatever', {
  Id : { type: DataTypes.INTEGER, allowNull: false, 
         defaultValue: null, primaryKey: false},
  // other columns you have...
});

查看该示例,DataTypes似乎是一个对象,INTEGER是其库中的属性。因此,如果您引用其库,那么您将能够使用这些类型。

最新更新