简体   繁体   English

如何从数组获取索引-graphql?

[英]How to get index from array - graphql?

I need to know the array item index when it's not returned by downstream response. 我需要知道下游响应未返回的数组项索引。 Suppose my schema looks like 假设我的架构看起来像

schema:
type Cart {
   items: [Item]
}

type Item {
   name: String
   index: Int
}

data comes: 数据来自:

 {items: [{name: apple}, {name: mango},]}

resolvers look like: 解析器如下所示:

Cart: {
   items(obj, context, info) {
     return obj;
   }
}

Item: {
   name(obj, context, info) {
     return obj.name;
   }
   index(obj, context, info) {
     // how to get it?
   }
}

How to get ith index in items array? 如何在项目数组中获取ith index

If you want to reutrn multiple item for one card in item then 如果您想为一张卡片中的一张卡片撤消多个物品,则

  type Cart {
     items: [Item]!
  }
  type Item {
     name: String!
     index: Int!
  }

  Query {
    cardItems: [Cart]!
  }
 resolver {
   cardItems : () => {
    //Perform opration and make result like this to run query properly
    return [{ items: [{ name: 'name1', index: 0 }, ...]}]       
    //Which is array of items contain name and index
   }
  }
  // Query to get result
  {
    cardItems {
      items {
        name
        index
      }
    }
  }

But if you wan to specific index of item in a cart you should taken id or index unique key and make anohter query 但是,如果您要转向购物车中特定的物品索引,则应使用ID或索引唯一键并进行进一步查询

Query {
  itemById(itemId: String!): Item
}
resolver {
    itemById({ itemId }) {
    //perform opration and return item with respeact to itemId
    return { name: 'string', index: 1}
    },
}

//Query to get result
{
  itemById(itemId: "1"){
    name
    index
  }
}

resolver reutrn index or itemId based result. 解析器查询索引或基于itemId的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM