Home > Back-end >  Return specific value from an object
Return specific value from an object

Time:06-06

Fetching a word from this API(https://api.dicionario-aberto.net/random) gives me the whole object:

{
  "word": "linguaraz",
  "wid": 74891,
  "sense": 1
}

How can I get to return only the word value in this object?

This is my code:

const getWord = async function () {
    const response = await fetch ("https://api.dicionario-aberto.net/random?get.value")
    const words = await response.text();
    const wordArray = words.split("\n");
    const randomIndex = Math.floor(Math.random() * wordArray.length);
    word = wordArray[randomIndex].trim();
    placeholder(word);
};

CodePudding user response:

You need to convert your api result into JSON first instead of text, then it will be easier to access word, like this

async function getData(){
   res = await fetch('https://api.dicionario-aberto.net/random');
   data = await res.json();
   console.log(data.word);
}
getData();

CodePudding user response:

Convert fetch data to json and read it as object property:

const getWord = async function () {
  const response = await fetch ("https://api.dicionario-aberto.net/random?get.value")
  const words = await response.json();
  placeholder(word);
};

CodePudding user response:

Convert to JSON using:

const obj = JSON.parse(await response)

or

const obj = await response.json()

Get value by entering key:

obj.<key_name>
  • Related