[Vuejs]-Vue โ€“ Right way to merge two different types of data

0๐Ÿ‘

3 things to do:

  • No need to transform API data directly, use computed values from 2 arrays.
  • Add identifier to inform rendering logic the type of item in array. A boolean isMessage will do.
  • Add new unique id for items in array if your ids for messages and events could be similar.

If you use vuex, the good way is to use getters to get the computed value. In here I will provide a sample of using Vueโ€™s computed.

<template>
    <div>
        <div v-for="item in combinedArray" :key="item.combinedId">
            <div v-if="item.isMessage">this is a message</div>
            <div v-else>this is an event</div>
        </div>
    </div>
</template>
<script>
export default {
    props: [ 'messages', 'events' ],
    computed: {
        combinedArray() {
            const array = [
                ...this.messages.map(m => ({
                    combinedId: `message_${m.id}`,
                    isMessage: true,
                    ...m
                })),
                ...this.events.map(e => ({
                    combinedId: `event_${e.id}`,
                    isMessage: false,
                    ...e
                }))
            ]
            return array.sort((itemA, itemB) => new Date(itemA.created_at) - new Date(itemB.created_at))
        }
    }
}
</script>

Leave a comment