When working with Vue.js, there may be times when you need to insert an array of objects at a specific index within another array. This is a common operation when working with dynamic lists or tables.
To achieve this in Vue.js, you can use a combination of the splice
method and the spread operator
. The splice
method allows you to add or remove elements from an array, while the spread operator
can be used to combine arrays or objects.In this tutorial we will learn how to insert an array of objects at a specific position in an array using Vue.js and native javascript method.
How to insert an array of objects at the Nth position in another array using Vue.js?
This code is a Vue.js application that creates a list by merging two arrays (oldArray
and newArray
) at a specific position (positionToInsert
) and displays the resulting list in the DOM using a v-for
directive.
When the application is mounted, the mounted()
lifecycle hook is called, which splits the oldArray
into two parts using the splice()
method and then merges the two parts with the newArray
using the spread (...
) operator to create a new array (updatedList
). Finally, the updatedList
is bound to the v-for
directive to display each item’s uid
and name
in the DOM.
Vue Js Insert an array of objects at the 4th position in an existing array Example
<div id="app">
<div v-for="item in updatedList" :key="item.id">{{ item.uid }} {{ item.name }}</div>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
oldArray: [
{ uid: 101, name: 'John Resig' },
{ uid: 102, name: 'Linus Torvalds' },
{ uid: 103, name: 'Ada Lovelace' },
],
newArray: [
{ uid: 342, name: 'Yukihiro Matsumoto' },
{ uid: 343, name: 'Anders Hejlsberg' },
{ uid: 342, name: 'Andrew' },
],
positionToInsert: 2,
updatedList: [],
};
},
mounted() {
const part1 = this.oldArray.splice(0, this.positionToInsert);
const part2 = this.oldArray;
this.updatedList = [...part1, ...this.newArray, ...part2];
},
});
app.mount('#app');
</script>