Skip to content

JavaScript push object into the array at index | Example code

  • by

Use the splice() method to push an object into the array at the index in JavaScript. The below code will insert item into arr at the specified index (deleting 0 items first, that is, it’s just an insert).

arr.splice(index, 0, item);

JavaScript push object into the array at the index

Simple example code push object in specified index position in the array.

<!DOCTYPE html>
<html>
<body>

  <script>
    var items_local = [
    {
      "size": "10",
      "status": true,
      "id": "QmzeJgg2F2"
    }
    ];

    const obj = {name: 'Tom'};

    items_local.splice(1, 0, obj);

    console.log(items_local)

  </script>

</body>
</html> 

Output:

JavaScript push object into the array at index

Replace existing object at the index

<script>
    var tableHeader = [{
      key: 1,
      value: 'inputname',
      defaultChecked: true,
      columnName: 'input.name',
    }, {
      key: 3,
      value: 'callname',
      defaultChecked: true,
      columnName: 'call.name',
    }, {
      key: 4,
      value: 'rank',
      defaultChecked: true,
      columnName: 'call.rank',
    }, {
      key: 5,
      value: 'threshold',
      defaultChecked: true,
      columnName: 'call.threshold',
    }, {
      key: 9,
      value: 'matchname',
      defaultChecked: true,
      columnName: 'match.name',
    }, ]

    console.log('Original', tableHeader)

    //Filter out {key:3}
    tableHeader = tableHeader.filter(function(e) {
      return e.key !== 3
    })

    tableHeader.push({
      key: 3,
      value: 'Hello',
      defaultChecked: true,
      columnName: 'call.name',
    })
    tableHeader.sort(function(a, b) {
      return a.key - b.key
    })

    console.log('Updated', tableHeader)
</script>

How to insert an item into an array at a specific index JavaScript?

Answer: In this example, we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());

361

You can implement the Array.insert method by doing this:

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

Then you can use it like:

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading