I have a small problem, I get my ref object from that method
JavaScript
x
8
1
const dataAnimals = ref([])
2
function getDataAnimals() {
3
axios.get('/json/data_animal.json').then((response) => {
4
dataAnimals.value = response.data
5
})
6
}
7
getDataAnimals()
8
And i want to use another method using that ref object :
JavaScript
1
10
10
1
function countAnimal(type) {
2
dataAnimals.forEach((item) => {
3
if (animal.animal == type) {
4
total_hen += dataMint.value[animal.template_id]
5
}
6
return total_hen
7
})
8
}
9
const totalHen = countAnimal('hen')
10
But i can’t iterate through :
JavaScript
1
2
1
dataAnimals.value.forEach((item) => {
2
Is there anyway to make that work ?
Thank you 🙂
Advertisement
Answer
As the response is an object and not an array, you cannot iterate over it with forEach
, you need to use Object.entries()
JavaScript
1
11
11
1
function countAnimal(type) {
2
let total = 0;
3
for (const [key, item] of Object.entries(dataAnimals)) {
4
if (item.animal === type) {
5
total++;
6
}
7
}
8
return total;
9
}
10
const totalHen = countAnimal('hen');
11
And I would use a reactive object:
JavaScript
1
8
1
const dataAnimals = ref(null);
2
function getDataAnimals() {
3
axios.get('/json/data_animal.json').then((response) => {
4
dataAnimals.value = response.data
5
});
6
}
7
getDataAnimals()
8
Of course if you want that count to be reactive as well you’d need to use a computed property.