英文:
Cypress Intercept Maneuvering Interchangeable Response Body Object Name
问题
我想要获取响应体中深层对象树中的一个值。以下是Cypress代码:
```javascript
cy.intercept('GET', 'https://api.staging.ethicalstg.com.au/organisations/*').as('search')
cy.wait('@search').its('response.body')
.then((body) => {
cy.log(body.data.entities.users)
})
这是结果日志
结果日志
我想要获取的是Id,在具有相同Id名称的对象内。该Id根据登录的帐户而变化。如何获取Id号码?
我已经尝试将日志更改为:
cy.log(body.data.entities.users[0])
但它返回空值
<details>
<summary>英文:</summary>
Good day, I'm trying to get a value from a response body that located deep into the object tree.
This is the Cypress code
cy.intercept('GET', 'https://api.staging.ethicalstg.com.au/organisations/*').as('search')
cy.wait('@search').its('response.body')
.then((body) => {
cy.log(body.data.entities.users)
})
and this is the result log
[results](https://i.stack.imgur.com/g6Xl5.png)
What I want to get is the Id, inside the object named with the same Id I want to get.
The id is changed depending on the account that logged in.
How do I get the Id number??
I've tried changed the log to:
cy.log(body.data.entities.users[0])
but it return empty
</details>
# 答案1
**得分**: 1
```js
// 使用 `Object.values` 将对象的属性转换为数组,然后使用索引。
const users = body.data.entities.users
const id = Object.values(users)[0].id
或者如果你只想要 id,可以使用 Object.keys
,因为它也恰好是 users
映射对象的键。
const users = body.data.entities.users // 映射对象
const id = Object.keys(users)[0]
英文:
Use Object.values
to convert an object's properties into an array, then use indexing.
const users = body.data.entities.users
const id = Object.values(users)[0].id
or if you only want the id, use Object.keys
because it also happens to be the key of the users
mapping object.
const users = body.data.entities.users // mapping object
const id = Object.keys(users)[0]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论