user14241810
user14241810

Reputation:

How to filter a map field array

I have the following array of items that i map to get a result

 var items = $.grep($.selections);

in which items looks as follows:

0: {ID: "310882", Type: "W", Total: 10}
1: {ID: "31094", Type: "W",  Total: 10}
2: {ID: "307969", Type: "W",  Total: 10}
3: {ID: "311951", Type: "W",Total: 10}
4: {ID: "ItemCover_1611315351331", Type: "F", Total: 5, AmountDue:55}

so what i wanted to do was to get all of the Totals which i can as follows

var AllTotal=items.map(x => x.Total);

which gives me the bellow result

0: 10
1: 10
2: 10
3: 10
4: 5

the question i have if you notice this item in the array

4: {ID: "ItemCover_1611315351331", Type: "F", Total: 5, AmountDue:55}

it has an ID: starting with "ItemCover" and it has AmountDue of 55

when i have an item of such nature how can i filter the Total of 5 out and replace it with the Amount Due so that it should now look like this

var AllTotal
   0: 10
    1: 10
    2: 10
    3: 10
    4: 55

Upvotes: 0

Views: 51

Answers (2)

laruiss
laruiss

Reputation: 3816

If the value of ID property starts with 'ItemCover', get the value of AmountDue property, otherwise, get the value of the Total property

items.map(x => x.ID.startsWith('ItemCover_') ? x.AmountDue : x.Total)

You can read more info on String.prototype.startsWith() and ternary operator

Upvotes: 0

mplungjan
mplungjan

Reputation: 177721

Simplest version assuming you want AmountDue if it exists

const arr = [{ID: "310882", Type: "W", Total: 10},
 {ID: "31094", Type: "W",  Total: 10},
 {ID: "307969", Type: "W",  Total: 10},
 {ID: "311951", Type: "W",Total: 10},
 {ID: "ItemCover_1611315351331", Type: "F", Total: 5, AmountDue:55}];

 const newArr = arr.map(({Total,AmountDue}) => AmountDue || Total)

 console.log(newArr)

Upvotes: 2

Related Questions