0

I'm, using yandex api translate to detect language from input value. First fetch return a language ui code as a string. Than i'm using another one fetch to transform that code to a name of this language (en -> english).

const getLang = (lang) => {
    fetch(`https://translate.yandex.net/api/v1.5/tr.json/getLangs?ui=en&key=${key}`)
        .then(response => {
            if (response.ok) return response
        })
        .then(response => {
            return response.json();
        })
        .then(data => {
            console.log(data.langs.lang);
        })
}

getLang function return me undefined because lang is a string. When I',m typing "data.langs.en" in console function return "English". How can I remake my variable lang?

Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23

3 Answers3

0

You can access the property using Property accessors:

const getLang = (lang) => {
    fetch(`https://translate.yandex.net/api/v1.5/tr.json/getLangs?ui=en&key=${key}`)
        .then(response => {
            if (response.ok) return response
        })
        .then(response => {
            return response.json();
        })
        .then(data => {
            console.log(data.langs[lang]);
        });
}
Yaelet
  • 160
  • 10
0

you must use data.langs[lang] in to last "then".

Hossein Akbarzadeh
  • 315
  • 1
  • 2
  • 11
-1

try this:

const getLang = (lang) => {
    fetch(`https://translate.yandex.net/api/v1.5/tr.json/getLangs?ui=en&key=${key}`)
        .then(response => {
            if (response.ok) return response
        })
        .then(response => {
            return response.json();
        })
        .then(data => {
            console.log(data.langs[lang]);
        })
}
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23