[英]Render object value filtered against another array
我有 2 個數組:
borders=[US, UK, CAN]
list=[{country:United States, code:US}, {country:United Kingdom, code:UK}
如果list.code
在邊框中,我想呈現list.country
。 我已經嘗試鏈接.map()
和.filter()
並且還減少了(我認為不正確)但未能實現所需的行為。
解決這個問題的最佳方法是什么?
最好的方法是做這樣的事情:
listFiltered() {
return list
.filter(({code}) =>
borders.includes(code)
)
}
鑒於這些數組:
borders=['US', 'UK', 'CAN']
list=[{country:'United States', code:'US'}, {country:'United Kingdom', code:'UK'}]
我不喜歡在這些情況下使用箭頭函數(像我一樣):
list.filter(function(element){ return borders.includes(element.code) })
這將過濾列表中的元素。 要僅獲取國家/地區,只需在末尾附加 .map() ,僅返回 element.country :
list.filter(function(element){ return borders.includes(element.code) }).map(function(element){ return element.country })
使用箭頭函數:
list.filter((element) => borders.includes(element.code)).map((element) => element.country )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.