Search code examples
javascriptjquerysalesforce-lightning

Add array value dynamically with a specific index?


createObjectDataadd: function(component, event) {
    var index = event.getParam("indexVar");
    console.log(index);

    var RowItemList1 = component.get("v.QuotelinitemList"); 
     RowItemList1.push({
        'sobjectType': 'Quote_Line_Item__c',
        'Name':'',
        'Client_P_N__c': ''
         });
     RowItemList1.splice(index+1,0,RowItemList1); 

    //  for (var i = index; i <RowItemList1.length; i++) { 
    //  RowItemList1.splice(index+1,0,rowli); 
    //    }              
    component.set("v.QuotelinitemList", RowItemList1);
    //RowItemList1.splice(index-1,0,RowItemList1); 
},

Quote_Line_Item__c is an object. suppose it has three records. Every record has index value. Every record has button new quote_line_item button which it is pushing a new quote line item record at end of the array.

My problem is it adding at the last index.I want to add it on next index where the record new quote line item button is pressed.

I tried many ways but it is not coming.


Solution

  • For adding item at specified index in Array, you can use "Array.splice" like below. It takes 3 arguments: index, number of items to remove from that index, new value(s) to add. So, trick is you can pass 0 as second argument which means you do not want to delete any item

    let arr = [1,2,3,4]
    
    function addItem(item, index) {
      arr.splice(index, 0, item)
    }
    
    addItem(10, 1)
    console.log(arr)