Reputation: 347
I am trying to parse a list of objects in a JSON payload into a table using Vue.js.
I want to take the keys from the first object in the array to create the table headings, the code below works and provides the correct values, but the problem is I keep getting this error message
The Error message
[Vue warn]: Error in render function: "TypeError: objectArray is null"
(found in <Root>)
The Html element
<thead>
<tr>
<th v-for="(value, key) in objectArray[0]">
{{ key }}
</th>
</tr>
</thead>
The JSON payload
[
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" },
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" },
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" }
]
The Vue code to populate the object
var link = 'api/array';
new Vue ({
el: '#app',
data: {
objectArray: null
},
methods:{
getObjectArray: function(){
this.$http.get(link).then(function(response){
this.objectArray = response.data;
}, function(error){
console.log(error.statusText);
});
}
},
mounted: function () {
this.getObjectArray();
}
});
Upvotes: 0
Views: 2679
Reputation: 1941
The error is because the objectArray is null the first time and isn't a Array. Try this code to prevent the error until your request is loaded:
<thead v-if='objectArray'>
<tr>
<th v-for="(value, key) in objectArray[0]">
{{ key }}
</th>
</tr>
</thead>
Upvotes: 5