Cypress拦截操纵可互换响应体对象名称

huangapple go评论60阅读模式
英文:

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&#39;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(&#39;@search&#39;).its(&#39;response.body&#39;)
        .then((body) =&gt; {
            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&#39;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]

huangapple
  • 本文由 发表于 2023年6月8日 09:32:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76428054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定