How do i extract the label in the countryOptions array based on the index on the checkbox?
const checkbox = [1, 2]
export const countryOptions = [
{
label: 'Malaysia',
index: 1,
},
{
label: 'Singapore',
index: 2,
},
{
label: 'Brazil',
index: 3,
},
]
Example output:
const country = ['Malaysia', 'Singapore']
CodePudding user response:
- Define the countries array
- Iterate through checkbox array
- for each checkbox array item, find the matching index in the country array
- if a country is found, add its label to the countries array
Assuming that the country index is a number, and checkbox array always holds numbers.
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.
}
})
CodePudding user response:
This a classic use case for filter
and map
:
- filter the array by checking if the index is included in
checkbox
- map the matching objects to their respective label
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);