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

标签 javascript arrays node.js express graphql

当下游响应未返回数组项索引时,我需要知道数组项索引。假设我的架构看起来像

schema:
type Cart {
   items: [Item]
}

type Item {
   name: String
   index: Int
}

数据来了:

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

解析器看起来像:

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

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

如何获取items数组中的第i个索引

最佳答案

如果您想为项目中的一张卡重新显示多个项目,则

  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
      }
    }
  }

但是,如果您想要购物车中商品的特定索引,您应该获取 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
  }
}

解析器返回基于索引或 itemId 的结果。

关于javascript - 如何从数组中获取索引 - graphql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55068107/

相关文章:

javascript - 如何使用 Jquery 或 Javascript 定位附加元素,或者如何将附加元素添加到 DOM?

javascript字符串替换特殊字符

javascript - 如何动态添加必需的输入元素?

arrays - 如果数组有,则可以在 O(n) 中排序

c - 使用 malloc 时出现段错误

javascript - 编译nodejs代码以实现更安全的分发

ios - 尝试执行 pod install "[!] FBReactNativeSpec has added 1 script phase."时出现错误

javascript - Angular ng-if 保存对 DOM 元素的引用

python - numpy:索引问题

css - 将自定义包含路径文件夹添加到 LESS.build