0

I have an array of objects as

array = [{"key": "English", "value": "en-ca"}, 
{"key": "French", "value": "fr-ca"}];

I am detecting the browser language using the following:

var brwsrlang = window.navigator.language;

I need to match the obtained browser language(brwsrlang) with the value in my array and return the matching string "en-ca".

For example: If my broswer language is "en-ca" it should return true or else false. I tried the following way. But, I want to make it work with the array values.

const x = brwsrlang.match( /[a-z]|-/g).join('');

This gives me the following result.

Output x=:
"en-ca"

But, I don't want to match it with all the alphabets. I just want it to check from the given array. I want to replace the regex with my array values.

2
  • Why are the objects { key: 'English', value: 'en-ca' } instead of { "english": "en-ca" }? Commented Apr 5, 2021 at 20:32
  • const inArray = array.some(language=> language.value.toLowerCase() === brwsrlang.toLowerCase()); Commented Apr 5, 2021 at 20:37

1 Answer 1

1

I'd turn the array into an object, eg into

{
  'en-ca': 'English',
  'fr-ca': 'French',
}

Ideally, do this once, in advance - eg, restructure your source code to an object of this structure.

Then just use bracket notation to look up the language on the object.

const languagesObj = Object.fromEntries(
  array.map(
    ({ key, value }) => [value, key]
  )
);
const thisLanguage = languagesObj[window.navigator.language];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.