Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

javascript - 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
question from:https://stackoverflow.com/questions/65846768/how-to-filter-a-map-field-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...