Search code examples
javascriptecmascript-6salesforce-lightning

merge two javascripts array objects by adding index based on count


I have the following object:

index;
@track cashList = [{Id: "",Index: index }];

My service outputs below object array:

result = [{Id:"100"},{Id:"101"},{Id:"102"}];

after merging with the result, cashList should look like

@track cashList = [{Id: "100",Index: 0 },{Id: "101",Index: 1 },{Id: "102",Index: 2 }];

cashList = result; //This one populating `Id` but not sure how to populate index

Any help would be appreciated.


Solution

  • you can map over an array and pass in the index so in the below ...item means you are keeping the existing object and adding in the index.

    result.map((item,index) => ({
        ...item,
        index
    }))