Search code examples
javascriptloopsiteratorvuejs3

Vuejs Iterate through a ref object


I have a small problem, I get my ref object from that method

const dataAnimals = ref([])
function getDataAnimals() {
  axios.get('/json/data_animal.json').then((response) => {
    dataAnimals.value = response.data
  })
}
getDataAnimals()

And i want to use another method using that ref object :

function countAnimal(type) {
  dataAnimals.forEach((item) => {
    if (animal.animal == type) {
      total_hen += dataMint.value[animal.template_id]
    }
    return total_hen
  })
}
const totalHen = countAnimal('hen')

But i can't iterate through :

dataAnimals.value.forEach((item) => {

Is there anyway to make that work ?

Thank you :)


Solution

  • As the response is an object and not an array, you cannot iterate over it with forEach, you need to use 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');
    

    And I would use a reactive object:

    const dataAnimals = ref(null);
    function getDataAnimals() {
        axios.get('/json/data_animal.json').then((response) => {
            dataAnimals.value = response.data
        });
    }
    getDataAnimals()
    

    Of course if you want that count to be reactive as well you'd need to use a computed property.