0

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']

2 Answers 2

1

This a classic use case for filter and map:

  1. filter the array by checking if the index is included in checkbox
  2. 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);

Sign up to request clarification or add additional context in comments.

Comments

1
  1. Define the countries array
  2. Iterate through checkbox array
  3. for each checkbox array item, find the matching index in the country array
  4. 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.
  }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.