I am trying to implement a logic that, i want to push some objects into the array after a specic index like, In a array have 5 objects then , i want to push two new objects after 3 index in current array. How can i do it.
const currarr = [{id:1,name:"abc"},{id:2,name:"efg"},{id:3,name:"hij"},{id:4,name:"klm"},{id:5,name:"nop"}];
otherObj = [{id:6,name:"fdf"},{id:7,name:"gfg"}]
I want to push the two new objects of otherObj array into the currarr array after the 3 index.
CodePudding user response:
curarr.splice(3, 0, ...otherObj)
CodePudding user response:
With the splice method, you can add or delete elements from a specific index.
For more resources.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
const currarr = [{id:1,name:"abc"},{id:2,name:"efg"},{id:3,name:"hij"},{id:4,name:"klm"},{id:5,name:"nop"}];
const otherObj = [{id:6,name:"fdf"},{id:7,name:"gfg"}]
currarr.splice(3, 0, ...otherObj)
console.log(currarr)
CodePudding user response:
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.