How to turn API Response into an iterable constant?

I am getting a Response from an API using the fetch method that looks like this:

Response (60 bytes) {
  ok: true,
  url: "https://xxxxx.xxx/xxx/xxx",
  statusText: "Multi-Status",
  redirected: false,
  bodyUsed: false,
  status: 207,
  Blob (60 bytes)
}

I can print the value to the tconsole by using res.json().then() like this:

    res.json().then(res => {
        if (res) { //check if there is an order ID
            console.log(`Cancelled existing orders\n${JSON.stringify(res)}`);
        }

This logs to the console the following object:

[
    {
    "id":"9eec57d1-f964-410b-ba82-274ec729fbf4",
    "status":200
  },
    {
    "id":"9eec57d1-f964-410b-ba82-274ec729abc7",
    "status":200
  },
]

The problem is that this JSON object is not iterable. I want to turn the response into an iterable object and assign it to a constant so I can check if its key values matches a condition, like this:

  await this.api.cancelOrders().then(res => {
      if (res.ok) {
          //What is the step here to turn "res" into an object that I can iterate over?
              if (res) {
                  //Do something with the object
              }
              else {
                  //Do something else
              }
      } else {
          throw new Error(`${res.status} ${res.statusText}`);
      }
  });

How do I do this? I have been ripping my hair out trying to figure out how to do it and would really appreciate some help :thinking:

add then that do then(data => data.json) so you get the object and you can work on it

Thank you for your reply @ilenia

What I want to do is get the object and access its properties, either by object accessors or through a loop. I am not sure how this can be achieved.

If I do console.log("res.json: ", res.json) I see in the console:

res.json: [Function: json]

And if I do res.json().then(data => console.log(data["id"])) or res.json().then(data => console.log(data.id))

I see in the console:

undefined

What am I missing?

If I do console.log("res.json: ", res.json) I see in the console:

res.json: [Function: json]

Right, because that is a method/function. You need to call it. What if you do console.log("res.json: ", res.json())

And if I do res.json().then(data => console.log(data["id"])) or res.json().then(data => console.log(data.id))

I see in the console:

undefined

OK,

res.json().then(data => console.log(data["id"]))`

Does data have a property by that name? It looks to me like it is an array.

Here are a couple of ways I can do it:

const getData1 = async () => {
  fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => console.log('data 1', json))
}

const getData2 = async () => {
  const rawResponse = await fetch('https://jsonplaceholder.typicode.com/users')
  const data = await rawResponse.json()
  console.log('data 2', data)
}

getData1()
getData2()

Thank you @kevinSmith !

I am still learning the basics and still find it a bit overwhelming.

But with your help I solved it like you said:

await this.api.cancelOrders()
    .then(res => {
        if (res.ok) return res;
        else {
            throw new Error(`${res.status} ${res.statusText}`);
        }
    })
    .then(res => res.json())
    .then(json => {
        console.log("ID", json[0].id);
    })

But what if I want to iterate the json object, something like this:

  .then(json => {
      for (const order of json) {
          console.log(order["id"]);
      }
  })

This will throw the type error Type 'JSON' must have a '[Symbol.iterator]()' method that returns an iterator.ts(2488)

How do I turn a JSON object into an iterable? There must be a simple way without changing its prototype.

EDIT: It seems I am a bit tired today and I solved it:

            .then(json => {
                for (const order of Object.entries(json)) {
                    console.log(order);
                }
            })

I’m not sure why. Please confirm what this outputs:

  .then(json => {
      console.log('json', json)
      console.log('isArray', Array.isArray(json))
      for (const order of json) {
          console.log(order);
      }
  })

I came to see the answer and edited my above post. My apologies for taking your time unnecessarily.

The reason it didn’t work was that there were no orders that could be cancelled. I had to first create some new orders to try it out.

Object.entries() works fine.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.