I need to create a new array of objects from the existing array on vuejs.
example first array :
import { ref } from 'vue'; const base_array = ref([ {id: 1, name: Pill, timing: [morning, noon, evening, night]}, {id: 2, name: Tablet, timing: [morning, evening]}, ])
expected result :
const modified_array = ref([ {id: 1, name: Pill, timing: [morning]}, {id: 2, name: Pill, timing: [noon]}, {id: 3, name: Pill, timing: [evening]}, {id: 4, name: Pill, timing: [night]}, {id: 5, name: Tablet, timing: [morning]}, {id: 6, name: Tablet, timing: [evening]}, ])
I’ve tried forEach and looping the array, but seems can’t find the right function. Thank youu
Advertisement
Answer
This code should work
const modified_array = ref( base_array.value.flatMap(({timing, ...r}) => timing.map(timing => ({...r, timing:[timing]})) ) );
However, if you want modified_array
to be reactive to changes in base_array
– you’d want to use computed
not ref
for modified_array
as in the code snippet below
If you watch, then the modified_array output changes when the base_array changes after three seconds with this code
setTimeout(() => base_array.value[1].timing.push('reactive!!!'), 3000);
Anyway, here’s the example of fully functional code for vue3
const { ref, createApp, computed } = Vue; createApp({ setup() { const base_array = ref([ {id: 1, name: 'Pill', timing: ['morning', 'noon', 'evening', 'night']}, {id: 2, name: 'Tablet', timing: ['morning', 'evening']}, ]); const modified_array = computed(() => base_array.value.flatMap(({ timing, ...r }) => timing.map((t) => ({ ...r, timing: [t] })) ) ); setTimeout(() => base_array.value[1].timing.push('reactive!!!'), 3000); return { base_array, modified_array}; } }).mount('#app');
.as-console-wrapper { max-height: 0 !important; top: 0; }
<script src="https://unpkg.com/vue@next"></script> <div id="app"> <ul> <li v-for="({id, name}) in base_array" :key="id"> {{ id }}: {{ name }} </li> </ul> <ul> <li v-for="({id, name, timing}, i) in modified_array" :key="i"> {{ id }}: {{ name }} {{timing[0]}} </li> </ul> </div>