I want to read a json from a local url so that it can be displayed with chartjs but the data.map traversal tells me that it is not a function. I want to make the request through a fetch using map to traverse the json but I don't know if I'm using its structure correctly.
const url = "http://localhost:3000/temperatura";
const ctx = document.getElementById('myChart').getContext('2d');
const response = fetch(url)
.then(res => res.json())
.then(data=>{
const mes = data.map(e=>e.mes);
const valor = data.map(e=>e.valor_temp);
console.log(data)
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: mes,
datasets: [{
label: 'Temperatura',
data: valor,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
});
This is the json I want to read, it is hosted in mongodb atlas
{"error":"","body":[{"_id":"6328a8748479b531f4e5b578","mes":"Junio","valor_temp":75,"__v":0},{"_id":"6328a8928479b531f4e5b57c","mes":"Mayo","valor_temp":32,"__v":0},{"_id":"6328a89a8479b531f4e5b57e","mes":"Julio","valor_temp":25,"__v":0},{"_id":"6328a8a18479b531f4e5b580","mes":"Agosto","valor_temp":30,"__v":0},{"_id":"6328a8b48479b531f4e5b583","mes":"Septiembre","valor_temp":20,"__v":0}]}
What happens is that map is a function for arrays and you have an object, which has an array inside. So you must make a map to the data.body
You have to put: