skip to Main Content

I’m having trouble writing a function to iterate through a list, look up and replace if matched. This is what I have so far:

function lookupTests(tests) {
    for (var i = 0; i < tests.length; i++) { 
        const currentTest = tests[i];
        // check if the current fruit exists in the lookup table
        if (translation[currentTest]) {
            // replace the current fruit with its value from the lookup table 
            tests[i] = translation[currentTest]; 
        }
    } 
};
    
var translation = {
    'AMIK':'AMIK',
    'GROU':'GPW',
    'AASC':'ABW',
    'ICOO':'ABW',
    'HPLC':'HBEW',
    'SICK':'SICW',
};
var tests = lookupTests([AASC,GROU]);

The error message I am getting is

DETAILS:    TypeError: Cannot read property "AASC" from undefined

2

Answers


  1. The code worked as expected, you just need to add a return at the end of your function.

    Showing the code used in this instance.

    Login or Signup to reply.
  2. Seeing the answer before works and I wrote something too, I wanted to share this solution: Using Object.entries(), that way you you can have more control over the keys and values of the entry.

    function lookupTests(tests) {
      // Iterate the translations: 
      // Keys would be 'AMIK', 'GROU' ... e.g. the first part
      // Values would be 'AMIK', 'GPW' ... e.g. the second part
      Object.entries(translation).forEach(([translationKey, translationValue]) => {
      // Iterate the tests:
      // Keys would be 0, 1, 2, 3 ...
      // Values would be the array you provide e.g. ['AASC', 'GROU']
        Object.entries(tests).forEach(([testsKey, testsValue]) => {
          if (translationKey !== testsValue) return
          tests[testsKey] = translationValue
        })
      })
      return tests
    }
    
    var translation = {
        'AMIK':'AMIK',
        'GROU':'GPW',
        'AASC':'ABW',
        'ICOO':'ABW',
        'HPLC':'HBEW',
        'SICK':'SICW',
    };
    
    var tests = lookupTests(['AASC', 'GROU']);
    console.log(tests)  returns  ['ABW', 'GPW']
    

    Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search