I want to run through this JSON file and output the values under "states". e.g. Bayern - 220318. How can I access these values in a loop to show them in a list or table?
asked Jan 20, 2021 at 8:54
-
You'd want to use the Object.keys() function. Something like Let keys = jsonObject.keys(). for(let i=0;i<keys.length;keys++) { Console.log(jsonObject[keys[i]]); }Henrik Clausen– Henrik Clausen2021年01月20日 08:58:31 +00:00Commented Jan 20, 2021 at 8:58
3 Answers 3
If you want just the country names then you can define a computed property as below...
computed: {
getStates() {
return this.output.states; // assuming that you have stored the response in a variable called 'output' defined in the data section
}
}
this is how you call the computed and print it in your template using v-for
<div v-for="(stateObject, state) in getStates" v-bind:key="state">
<div>{{state}}</div> // to print the state name
<div>{{stateObject.total}}</div> // to print the total value of that object
<div>{{stateObject.vaccine}}</div> // to print the vaccine value of that object
</div>
answered Jan 20, 2021 at 9:41
17 Comments
Ralf Bordé
'<b-card no-body img-src="picsum.photos/300/150/?image=41" img-alt="Image" img-top tag="article" class="mb-2" v-for="result in getStates" v-bind:key="result.key"> <div style="margin:10px 10px 10px 10px;"> <h4>{{ result.states }}</h4>' I want to print the values with this vue-html. how can i achieve this?
Ralf Bordé
your answer overlapped with my question. Thank you.
Ralf Bordé
Yes I will do so. But how can i print the "total" or "vaccinated"-value behind the "state"? In "index" there is only a counter.?
Amaarockz
I have modified the computed and template block ...check the updated answer
Ralf Bordé
OK, Thanks, but it doesn't work. Only the key 0,1,2,... is printed.
|
Use Object.keys()
to iterate the object by keys.
Object.keys(output.states).forEach(key => {
console.log(key, output.states[key].vaccinated);
});
answered Jan 20, 2021 at 8:58
4 Comments
Ralf Bordé
THX, yes in this way I can loop through, but I want to have the name of the country e.g. Bayern, Berlin, Brandenburg etc.
topdev87
key
is the country name in your case.Ralf Bordé
and how can I use these values to output in vue with v-for? Do I need to save them in an array beforehand?
topdev87
yes, you can use computed and object.keys for return keys as value
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
You can read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
answered Jan 20, 2021 at 9:30
3 Comments
Ralf Bordé
THX, but how can I use it in vue to print the values with v-for?
Amaarockz
Do you want to print it one by one?
Endre Szabó
You could store it in a data attribute (like in an array, instead of console log just push it in to one) and then v-for on that array :)
lang-js