[英]Use a field alias as the key of a javascript object
How do I use a field alias as the key of a javascript object?如何使用字段别名作为 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}`
This obviously returns ctry is not defined
error as ctry
is considered a javascript variable.这显然返回
ctry is not defined
错误,因为ctry
被认为是一个 javascript 变量。 Is there a way to make this query return values of keys in the countries
object when the key is retrieved from database?当从数据库中检索键时,有没有办法让这个查询返回
countries
对象中键的值?
And this done:这样做了:
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}`
To do this in json object you need to use a for:要在 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)
I can't do more with your information.我不能用你的信息做更多。
Convert your countries
object into an array using Object.entries
then .map
them to output WHEN '${i[0]}' THEN '${i[1]}'
.使用
Object.entries
将您的countries
对象转换为数组,然后将它们.map
到输出WHEN '${i[0]}' THEN '${i[1]}'
。 This will give you the WHEN
parts for each country.这将为您提供每个国家/地区的
WHEN
部分。 Just append this string into your query
( CASE country \\n${caseStr}\\nEND
) then you'll have the full CASE Statement built for you.只需将此字符串附加到您的
query
( CASE country \\n${caseStr}\\nEND
),然后您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);
Why store it in JSON though?为什么将它存储在 JSON 中? It looks like you can access the DB anyway, why not store the countries in a table to which you can
JOIN
your query to?看起来您无论如何都可以访问数据库,为什么不将国家/地区存储在您可以
JOIN
查询的表中?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.