javascript - 如何在 JS 函数中动态设置键值?
问题描述
我正在使用以下代码:
var list = ['product', 'city', 'village'];
const foobar = new GraphQLObjectType({
name: 'foobarType',
fields: () => ({
product :{ // <== NOTE THAT PRODUCT IS IN THE LIST
type: new GraphQLList(foobarType),
args: {
certainty:{
type: GraphQLFloat,
description: "tester"
}
},
resolve(root,args){
return "foobar"
}
}
})
如您所见,我有一个list
包含三个项目的。在fields
函数中,你可以看到我有product
.
如何遍历列表以fields
在运行时动态设置函数,结果将是:
var list = ['product', 'city', 'village'];
const foobar = new GraphQLObjectType({
name: 'foobarType',
fields: () => ({
product :{ // <== RESULT FROM LIST
type: new GraphQLList(foobarType),
args: {
certainty:{
type: GraphQLFloat,
description: "tester"
}
},
resolve(root,args){
return "foobar"
}
},
city :{ // <== RESULT FROM LIST
type: new GraphQLList(foobarType),
args: {
certainty:{
type: GraphQLFloat,
description: "tester"
}
},
resolve(root,args){
return "foobar"
}
},
village :{ // <== RESULT FROM LIST
type: new GraphQLList(foobarType),
args: {
certainty:{
type: GraphQLFloat,
description: "tester"
}
},
resolve(root,args){
return "foobar"
}
}
})
})
解决方案
您可以遍历函数内的列表并使用object[item] = value;
语法添加每个项目。
fields: () => {
var fields = {};
list.forEach(item => {
fields[item] = {
type: new GraphQLList(foobarType),
args: {
certainty:{
type: GraphQLFloat,
description: "tester"
}
},
resolve(root,args){
return "foobar"
}
}
});
return fields;
}
不过,这种嵌套是丑陋的代码。我希望您在传递之前将字段保存在变量中。
const fields = {};
list.forEach(item => {
fields[item] = {
type: new GraphQLList(foobarType),
args: {
certainty:{
type: GraphQLFloat,
description: "tester"
}
},
resolve(root,args){
return "foobar"
}
}
});
const foobar = new GraphQLObjectType({
name: 'foobarType',
fields: () => fields
})
推荐阅读
- c++ - 如何在给定范围内打印出周长和直角三角形的数量?
- android - 如何使用 Django for Android 执行注册和登录 Api
- python - 学习正弦函数似乎在 ANN (Keras) 中采用了过多的参数
- python - OpenCV filter2d 给出不正确的结果
- android - 如何使用数组修复for循环中的应用程序崩溃
- sqlite - 截断使用 SDL RWops 打开的文件
- jquery - jQuery/JS ES5 - 查找数据属性的部分名称
- cucumber - 如何通过在范围报告中使用 Cucumber 和 Java 来获取“步骤”名称
- swift - 设置 Firestore 文档时如何检测不存在的网络连接
- r - R - 优化(最大)