如何在JS函数中动态设置键值?

时间:2018-06-08 14:24:13

标签: javascript node.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"
      }
    }
  })
})

2 个答案:

答案 0 :(得分:1)

您可以在函数内迭代列表,并使用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
})

答案 1 :(得分:0)

您可以使用数组的map函数和computed property names(括号)语法来执行此操作:

fields: () => list.map(item => ({
    [item]: {
        type: new GraphQLList(foobarType),
        args: {
          certainty:{
            type: GraphQLFloat,
            description: "tester"
          }
        },
        resolve(root,args){
          return "foobar"
        }
    }
}))