0

I have to do a translate function using a structure looking like:

let dict = [
    {
        en: "moon",
        de: "der Mond",
        hu: "hold",
        rs: "mesec"
    },
    {
        en: "fox",
        de: "der Fuchs",
        hu: "róka",
        rs: "lisica"
    },
    {
        en: "girl",
        de: "das Mädchen",
        hu: "lány",
        rs: "devojka"
    }
];

My function is:

function translate(word, from, to) {
    return dict.find(x => x.from == word).to
}

And how I have to call the function:

translate("fox", "en", "hu")

My from and to parameters just don't want to work and givinig back undifined. If I call it directly like: dict.find(x => x.en == "fox").hu it gives me the right value, which is "róka". I figured out maybe it's because of the quotes but I didn't find any solution anywhere.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Jack
  • 3
  • 3
  • 3
    When using a variable to access an object property you need to use bracket notation, so `dict.find(x => x[from] == word)[to]` see: [Property accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#syntax) – pilchard Feb 14 '21 at 22:27
  • Have a look at [*property accessors*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#bracket_notation). – Peter Seliger Feb 14 '21 at 22:33
  • depending on how big your dictionary is and how often you have to search there, it may be worth to use this format: `var dict2 = Object.fromEntries(dict.flatMap(obj => Object.entries(obj).map((kv) => [kv.join(":"), obj])));` because `translate` goes now from a `O(n)` to a `O(1)` operation. Like this: `function translate(word, from, to) { return dict2[\`${from}:${word}\`]?.[to] ?? word; }` – Thomas Feb 15 '21 at 03:24

1 Answers1

0

You get undefined as "from" is not a property of the array object and hence the method could not find any match.

Instead, you can use it in this way:

function translate (word, from, to) {
    const translation = dict.find(x => x[from] === word);
    return translation?.[to] ?? word; // returns back the same word if no match is found
}
Vishwajeet
  • 71
  • 1
  • 7