My service returns a JSON with irregular data structure as shown below:
dataFromService: [
{
event_data: '2021-03-18T15:20:31.314Z', // if !null = page
event_category: 'news',
event_title_en: 'page title',
},
{
event_list_news_events_event_data: 'not null', // if !null = doc
event_list_news_events: [
{ event_category: 'news' },
{ event_title: 'page title' }
],
publication_date: '2021-02-12T15:20:31.314Z'
}
...
]
The goal is to format the data using the following method:
newData: [
{
itemType: 'page',
itemCategory: 'news',
itemTitle: 'page title',
itemDate: '2021-03-18T15:20:31.314Z',
},
{
itemType: 'doc',
itemCategory: 'event',
itemTitle: 'doc title',
itemDate: '2021-02-12T15:20:31.314Z',
},
...
]
An approach to achieve this is demonstrated below:
var app = new Vue({
el: '#app',
data: function() {
return {
myList: []
}
},
created () {
this.dataSource();
},
methods: {
dataSource: function() {
for(var i = 0; i < this.dataFromService.length; i++) {
let elem = {};
if (this.dataFromService[i].event_data && this.dataFromService[i].event_data != null) {
elem['itemType'] = 'page';
elem['itemCategory'] = this.dataFromService[i].event_category;
elem['itemDate'] = this.dataFromService[i].event_data;
if (this.lang === 'en') {
elem['itemTitle'] = this.dataFromService[i].event_title_en;
}
} else if (this.dataFromService[i].event_list_news_events_event_data && this.dataFromService[i].event_list_news_events_event_data != null) {
elem['itemType'] = 'doc';
elem['itemCategory'] = this.dataFromService[i].event_list_news_events.event_category;
elem['itemDate'] = this.dataFromService[i].publication_date;
elem['itemTitle'] = this.dataFromService[i].event_list_news_events.event_title;
}
this.myList.push(elem);
}
console.log('myList: ', JSON.stringify(this.myList));
}
}
});
There are questions regarding optimization such as better ways than using the for loop and the best way to call the method, whether in "created", "beforeMount", or "mounted" hooks.