We can easily insert an object at a particular, known position in an array of objects. We can do so by first breaking the array into segments and then merging it accordingly.
Here I’ve shown an example to demonstrate the same:
const originalList = [
{ id: 1, name: 'Gautam' },
{ id: 2, name: 'Michael' },
{ id: 4, name: 'Robert' },
{ id: 5, name: 'David' },
]
const newPerson = {
id: 3,
name: 'John',
}
const insertionPosition = 3
const list1 = originalList.splice(0, insertionPosition - 1)
const list2 = originalList
console.log(list1)
console.log(list2)
const appendedList = [...list1, newPerson, ...list2]
console.log(appendedList)
Code language: JavaScript (javascript)
As you can see I have an array of objects containg id’s 1,2,4, and 5. Now I want to insert an object having id 3 at the 3rd position in the array.
First I’ve broken the array into two segments called list1 and list2. I’ve then appended all the elements of the lists (including the object to be pushed) into a new list called appendedList (as written on line 21).
The resultant list would look like:
[
{ id: 1, name: 'Gautam' },
{ id: 2, name: 'Michael' },
{ id: 3, name: 'John' },
{ id: 4, name: 'Robert' },
{ id: 5, name: 'David' }
]
Code language: JavaScript (javascript)
If you have any doubts or have a suggestion, sound off in the comments below!