Tengo un pequeño problema, obtengo mi objeto ref de ese método.
const dataAnimals = ref([]) function getDataAnimals() { axios.get('/json/data_animal.json').then((response) => { dataAnimals.value = response.data }) } getDataAnimals()Y quiero usar otro método usando ese objeto ref:
function countAnimal(type) { dataAnimals.forEach((item) => { if (animal.animal == type) { total_hen += dataMint.value[animal.template_id] } return total_hen }) } const totalHen = countAnimal('hen')Pero no puedo iterar a través de:
dataAnimals.value.forEach((item) => {¿Hay alguna forma de hacer que funcione?
Gracias :)
Como la respuesta es un objeto y no una matriz, no puede iterar sobre ella con forEach , necesita usar Object.entries()
function countAnimal(type) { let total = 0; for (const [key, item] of Object.entries(dataAnimals)) { if (item.animal === type) { total++; } } return total; } const totalHen = countAnimal('hen');Y usaría un objeto reactivo:
const dataAnimals = ref(null); function getDataAnimals() { axios.get('/json/data_animal.json').then((response) => { dataAnimals.value = response.data }); } getDataAnimals()Por supuesto, si desea que ese recuento también sea reactivo, deberá usar una propiedad calculada.