Necesito capturar cartID en una variable js de una respuesta JSON.
Hasta ahora tengo el siguiente código que solicita la información del carrito.
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));Los datos de console.log tienen este formato:
Extract of full data: [{"id":"c5f24d63-cd9a-46f2-be41-6ad31fc38b51","customerId":1,"email":"me@gmail.com", ................. }]Probé varios métodos para capturar la identificación del carro en la variable cartID, pero cada vez que aparece "desconocido" y se registra antes de la respuesta de datos.
¿Alguna idea de cómo retrasar hasta que la respuesta esté lista y luego 'cartID' con el valor de identificación?
Debido a que la respuesta es una matriz JSON, puede intentar hacer un bucle y extraer el ID del carrito de cada objeto del carrito:
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));