Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
Javascript: How to set variable to API response value fetch api?

Here is the code I am working with:

const encodedParams = new URLSearchParams();
encodedParams.append("q", "Hello, world!");
encodedParams.append("target", "es");
encodedParams.append("source", "en");

const options = {
    method: 'POST',
    headers: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept-Encoding': 'application/gzip',
        'X-RapidAPI-Host': 'google-translate1.p.rapidapi.com',
        'X-RapidAPI-Key': '3955ade317mshe662a97591d523ap1e4475jsn3bb2b223ccbb'
    },
    body: encodedParams
};

fetch('https://google-translate1.p.rapidapi.com/language/translate/v2', options)
    .then(response => response.json())
    .then(response => console.log(response))
    .catch(err => console.error(err));

Here is the response I receive from the API

{data: {…}}
data:
translations: Array(1)
0: {translatedText: '¡Hola Mundo!'}
length: 1
[[Prototype]]: Array(0)
[[Prototype]]: Object
[[Prototype]]: Object

How would I grab the translatedText from the API response and set a variable equal to that. I have tried TRANSLATED_TEXT = response.data.translations[0].translatedText;

I need to set a variable and then put the variable into a h1 on an HTML document. Any help with grabbing the API response would be appreciated!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

try response.data.translations[0].translatedText.value;

or response.data.translations[0].translatedText[0].text;

about 4 years ago · Juan Pablo Isaza Report

0

Found a similar example: https://rapidapi.com/googlecloud/api/google-translate1/discussions/21334

Try: response.data.data['translations'][0]['translatedText']

Hope it helps.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!