如何根據復選框上的索引提取countryOptions陣列中的標簽?
const checkbox = [1, 2]
export const countryOptions = [
{
label: 'Malaysia',
index: 1,
},
{
label: 'Singapore',
index: 2,
},
{
label: 'Brazil',
index: 3,
},
]
示例輸出:
const country = ['Malaysia', 'Singapore']
uj5u.com熱心網友回復:
- 定義國家陣列
- 遍歷復選框陣列
- 對于每個復選框陣列項,在國家陣列中找到匹配的索引
- 如果找到一個國家,將其標簽添加到國家陣列
假設國家索引是一個數字,并且復選框陣列始終包含數字。
let countries = [];
checkbox.forEach(countryIndex => {
let country = countryOptions.find(country => country.index ===
countryIndex);
if (country) {
countries.push(country.label);
} else {
//the country was not found, maybe an error you want to handle or notify the user.
}
})
uj5u.com熱心網友回復:
filter這是and的經典用例map:
- 通過檢查索引是否包含在陣列中來過濾陣列
checkbox - 將匹配的物件映射到它們各自的標簽
const checkbox = [1, 2];
const countryOptions = [{
label: 'Malaysia',
index: 1,
},{
label: 'Singapore',
index: 2,
},{
label: 'Brazil',
index: 3,
}];
let country = countryOptions
.filter(x => checkbox.includes(x.index))
.map(x => x.label);
console.log(country);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/459695.html
