Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
Get Cart Id from JSON response

I need to capture the cartID in a js variable from a JSON response.

So far I have the following code which requests the cart information.

function getCart(url) {
   return fetch(url, {
       method: "GET",
       credentials: "same-origin"
   })
   .then(response => response.json())
};

var cartID = 'unknown';

getCart('/api/storefront/carts')
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));

The console.log data is formatted like this:

Extract of full data:
[{"id":"c5f24d63-cd9a-46f2-be41-6ad31fc38b51","customerId":1,"email":"me@gmail.com", ................. }]

I have tried various methods to capture the cart ID to variable cartID, but each time it shows 'unknown' and is logged before the data response.

Any ideas how to delay until the response is ready and then 'cartID' with the id value?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because the response if a JSON array, you can try to loop and extract the cartID from each cart object:

function getCart(url) {
    return fetch(url, {
        method: "GET",
        credentials: "same-origin"
    })
    .then(response => response.json())
 };
 
 var cartID = 'unknown';
 
 getCart('/api/storefront/carts')
 .then(
     data => {
         //The response is an array of cart objects. We need to extract the ID from the array
         cartID = data[0].id;

         //Or loop through the response and extract the ID from each cart object
         for (var i = 0; i < data.length; i++) {
             cartID = data[i].id;
         }
     }
     )
 .catch(error => console.error(error));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda