-1

I have a JSON array as below,

this.sampleArray = [
      {
        "start_time": "",
        "end_time": ""
      },
      {
        "start_time": "",
        "end_time": ""
      },
      {
        "start_time": "",
        "end_time": ""
      },
      {
        "start_time": "",
        "end_time": ""
      },
      {
        "start_time": "",
        "end_time": ""
      },
      {
        "start_time": "",
        "end_time": ""
      },
      {
        "start_time": "",
        "end_time": ""
      }
    ];

I want to insert data to this array based on a value at a specific index. I am not sure how to proceed further. Any suggestions on how to proceed further would be appreciated.

Shinchan
  • 81
  • 2
  • 17
  • How do you mean you are not sure how to proceed, what have you tried except for typing your array here? Did you look at `splice`? – Icepickle Nov 05 '20 at 09:06

2 Answers2

2

You can easily replace with array splice method. Following code will replace existing item with new item.

sampleArray.splice(4, 1, {start_time: new Date(), end_time: new Date() });
Harun ERGUL
  • 5,770
  • 5
  • 53
  • 62
1

You could also use the deconstructing assignment

var arr = [1, 2, 3, 4, 5];

var insertValue = 8;
var insertAt = 1;

[...arr[insertAt]] = [insertValue, arr[insertAt]];

arr = arr.flat();

console.log(arr);
MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43