2

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 :)

Jérémy
  • 23
  • 1
  • 4
  • Are you sure, the `response.data` is actually returning an array? Maybe it is an object containing an array? – Thomas Nov 09 '21 at 09:46
  • Hello Thomas, here is the reponse.data content : https://prnt.sc/1yvhnkq and here is the dataAnimals : https://prnt.sc/1yvhsau – Jérémy Nov 09 '21 at 10:14

1 Answers1

1

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.

Thomas
  • 6,325
  • 4
  • 30
  • 65
  • Thank you, you really helped me ! Why would you use a reactive object instead of a ref object ? – Jérémy Nov 09 '21 at 21:34
  • There is no real rule for it, in this case ref would probably be even the better case (I'll edit the code). There is a good break down: https://stackoverflow.com/questions/61452458/ref-vs-reactive-in-vue-3 – Thomas Nov 10 '21 at 08:08
  • I'm using this exact format "for (const [key, item] of Object.entries(images))" but 'item' is another proxy object that looks exactly like the original images object, but with one element rather than many, so I have to use item[0].filename to get to the contents. Is this normal or have I stuffed something up? – maganthro Nov 24 '22 at 22:26
  • I had to use "for (const [key, item] of Object.entries(images.value))" to get this to work. – maganthro Nov 24 '22 at 22:31