-2

I want to insert object Specific index.

I research push and splice but I couldn't find a solution.

var collection = [ {id:"123"} ,{id:"567"}, {id:"999"} ] 

The result I'm looking forward to is

result :

[ {id:"123"} ,{id:"567"}, {id:"1111"}, {id:"999"} ] 
Eddie
  • 26,593
  • 6
  • 36
  • 58
mara
  • 29
  • 6

3 Answers3

2

Use splice:

var collection = [{id:"123"} ,{id:"567"}, {id:"999"}];
collection.splice(2, 0, { id: "1111" });
console.log(collection);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You can use splice method of Array collection.splice(index, value, numberOfElWillBeRemoved, numberOfElWillBeAdded) For more detail: https://www.w3schools.com/jsref/jsref_splice.asp

Nhut Dinh Ba
  • 354
  • 1
  • 6
0

You can loop trow array:

var collection = [{ id: "123" }, { id: "567" }, { id: "999" }];

for(var i = 0; i < collection.length; i++) {
    console.log(collection[i]);
}

And change the array length

collection.length = 4

Then replace location of any string. Just make new same array and replace the var

var newArray = collection;
collection[3] = newArray[2];

Now 2 index is free.