Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在graphql中过滤数组的正确方法_Graphql - Fatal编程技术网

在graphql中过滤数组的正确方法

在graphql中过滤数组的正确方法,graphql,Graphql,我有以下安排: const Person = function(name, age, interest) { this.name = name; this.age = age; this.interest = interest; } const people = [ new Person("rajat", 29, ['prog','food','gym']), new Person("ravi", 23, ['travel', 'cook', 'eat'

我有以下安排:

const Person = function(name, age, interest) {
    this.name = name;
    this.age = age;
    this.interest = interest;
}

const people = [
    new Person("rajat", 29, ['prog','food','gym']),
    new Person("ravi", 23, ['travel', 'cook', 'eat']),
    new Person("preeti", 19,  ['comedy', 'arts', 'beauty'])
];

const schema = buildSchema(`
    type Person {
        name: String,
        age: Int,
        interest: [String]
    },
    type Query {
        hello: String,
        giveTen(input: Int!): Int,
        person(name: String!): Person!, 
    }
`);

const root = {
    hello: () => 'Hello World',
    giveTen: (args) => args.input * 10,
    person: (args) => people.filter(item => item.name === args.name),
};
当我运行以下查询时:

query PersonDetails {
  person(name: "rajat") {
    name
    age
    interest
  }
}
当人员数组中有明显匹配的数据时,我得到一堆空值


您在解析器中返回的内容需要与该特定字段的类型匹配。在模式中,您指定了根查询字段person应该返回person类型,而不是该类型的列表数组

Array.prototype.filter始终返回一个数组

如果要从people返回单个对象,应改用Array.prototype.find,它将返回与测试匹配的第一个元素,如果找不到,则返回null


如果要返回所有可能的匹配项,则需要更改模式以反映将返回类型从Person更改为[Person]。然后您可以继续使用filter,它应该可以按预期工作。

我应该阅读更多关于Array.prototype.filter的内容。谢谢
{
  "data": {
    "person": {
      "name": null,
      "age": null,
      "interest": null
    }
  }
}