【问题标题】:Use a field alias as the key of a javascript object使用字段别名作为 javascript 对象的键
【发布时间】:2021-07-29 09:54:20
【问题描述】:

如何使用字段别名作为 javascript 对象的键?

const countries = {
    'united states of america': 'US',
    'india': 'IN',
    'china': 'CN'
}
const query = `SELECT country AS ctry, IF(true, '${countries[ctry]}', 'p') AS c FROM ${table}`

这显然会返回ctry is not defined 错误,因为ctry 被认为是一个javascript 变量。当从数据库中检索键时,有没有办法使此查询返回 countries 对象中键的值?

【问题讨论】:

  • 您需要使用CASE 语句编写正确的查询。
  • @VLAZ 我可以在CASE 语句中访问${countries[ctry]} 吗?我不想为所有国家提供案例,因为会有数百个。我打算将它存储在一个 json 文件中。

标签: javascript sql google-bigquery


【解决方案1】:

SQL CASE

这就完成了:

const countries = {
    'united states of america': 'US',
    'india': 'IN',
    'china': 'CN'
}
const query = `SELECT country AS ctry, CASE WHEN ctry='united states of america' THEN 'US' as c WHEN ctry='india' THEN 'IN' as c WHEN ctry='china' THEN 'CN' as c ELSE 'no country find' as c END FROM ${table}`

【讨论】:

  • 问题在于所有国家/地区都会有数百个案例。我希望将其存储在 json 文件中并动态访问它。有办法吗?
【解决方案2】:

要在 json 对象中执行此操作,您需要使用 for:

const countries = {
    'united states of america': 'US',
    'india': 'IN',
    'china': 'CN'
}
const query = `SELECT country AS ctry FROM ${table}`

//Execute here your request

let c = [];

for (let i = 0; i < query.length; i ++) {
  c.push(query[i]['country'])
}

for (let j = 0; j < c.length; j ++) {
  c[j] = countrie[c[j]]
}

console.log(c)

我不能用你的信息做更多的事情。

【讨论】:

    【解决方案3】:

    使用Object.entriescountries 对象转换为数组,然后将.map 转换为输出WHEN '${i[0]}' THEN '${i[1]}'。这将为您提供每个国家/地区的WHEN 部分。只需将此字符串附加到您的 query (CASE country \n${caseStr}\nEND) 中,您就可以为您构建完整的 CASE 语句。

    const table = 'test';
    const countries = {
      'united states of america': 'US',
      'india': 'IN',
      'china': 'CN'
    };
    const caseStr = Object.entries(countries).map(i => `WHEN '${i[0]}' THEN '${i[1]}'`).join('\n');
    
    const query = `SELECT country AS ctry \n, CASE country \n${caseStr}\nEND AS c FROM ${table}`
    console.log(query);

    为什么将它存储在 JSON 中呢?看起来您无论如何都可以访问数据库,为什么不将国家/地区存储在您可以JOIN 查询的表中?

    【讨论】:

      猜你喜欢
      • 2015-05-13
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 2015-09-04
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多