首页 > 解决方案 > 如何在 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"
      }
    }
  })
})

标签: javascriptnode.js

解决方案


您可以遍历函数内的列表并使用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
})

推荐阅读