How to iterate over this JSON?

Hello folks!
I have the following JSON file. I must iterate over the ID to display its data on screen (as id and name_on_card).

{
    "count_page": 1,
    "data": [
        {
            "id": 104,
            "card_last_numbers": "XXXX-XXXX-XXXX-4444",
            "name_on_card": "sadfsad432",
        },
        {
            "id": 103,
            "card_last_numbers": "XXXX-XXXX-XXXX-4444",
            "name_on_card": "asdfasdf",
        },
        {
            "id": 102,
            "card_last_numbers": "XXXX-XXXX-XXXX-4444",
            "name_on_card": "asdf",
        }
    ]
}

and I have the following function to be able to paint some data on the screen.

function loadCreditCard() {
	fetch(`${ base_url }creditcard.xyz/api/card/list/?id-company={{company.id}}`, {
		method: 'GET', 
		headers: {
			'Content-Type': 'application/json',
			"Authorization": `Bearer ${localStorage.getItem("jwtToken")}`,
			"X-CSRFToken": "{{csrf_token}}"
		}, 
	})
	.then(function (response) {
		if (response.ok) {
			return response.json()
		} else {
			return Promise.reject(response)
		}
	})
	.then(function (data) {
		document.getElementById("id_name").innerHTML = data.data[0].name_on_card;
		document.getElementById("id_card_number").innerHTML = data.data[0].card_last_numbers;
		document.getElementById("id_address").innerHTML = data.data[0].address;
		document.getElementById("id_zip_number").innerHTML = data.data[0].zip;
		document.getElementById("expire_date_years").innerHTML = data.data[0].expire_date.substring(0,4);
		document.getElementById("expire_date_months").innerHTML = data.data[0].expire_date.substr(-5);
		globalThis.GLOBAL_CARD_ID = data.data[0].id;
		console.log(GLOBAL_CARD_ID);
	})
	.catch(function (err) {
		console.log(err)
		setTimeout(() => {
			loadCreditCard()
		}, 3000)
	}); 
}

loadCreditCard()

But how can I iterate over that [0]?
Thanks in advance/

You have an array, could create a useful reference for it:

const cards = data.data;

cards.forEach(/* in here, create a function to display *one* card */)

The freecodecamp curriculum has some good exercises on working with arrays, and arrays of objects.

1 Like

But how can I write the number of the array (look the hightlight text)? If I write a for loop, it would be an error because is inside a forEach.

ok, I readt the manual. Thanks a lot! this was the solution, passing parameters:

	cardsData.forEach((v,i) => {
	const mainContainer = document.getElementById("main-container")
	const originalCard = document.getElementById("credit-card")
	const creditCard = originalCard.cloneNode(true)
	mainContainer.appendChild(creditCard)
	// I t e r a t e   t o   c h a n g e    t e x t
	document.getElementById("id_card_number").innerHTML = data.data[i].name_on_card;
})

You guys are lifesavers!

1 Like