lundi 28 octobre 2019

Loop for every x object in JSON aray

I'm working on this small project (extension) where I fetch data from a JSON array with rapidapi, I'm able to get the data. But i'm unclear and new to get how to loop thru the whole dataset (which eventually I would try to store on the localstorage, but that's irrelevant for know)

concrete: I want to loop randomly thru the whole array and show every 1ste object of every second array in the whole array.

example of JSON array

0:{4 items
"kanji":{6 items
"character":"一"  ----> this one
"meaning":{...}1 item
"strokes":{...}3 items
"onyomi":{...}2 items
"kunyomi":{...}2 items
"video":{...}3 items
}
"radical":{...}7 items
"references":{...}3 items
"examples":[...]9 items
}
1:{4 items
"kanji":{6 items
"character":"飼"  ----> or this one
"meaning":{...}1 item
"strokes":{...}3 items
"onyomi":{...}2 items
"kunyomi":{...}2 items
"video":{...}3 items
}
"radical":{...}7 items
"references":{...}3 items
"examples":[...]6 items
}

And so one.

I've tried to get the JSON array and show an object of it. Then I tried to change the [1] number to a variable. But there I got stuck. I can't figure out how to create a random generator that picks every 1st object of the array like shown in the json array above.

var myfetch = fetch("https://kanjialive-api.p.rapidapi.com/api/public/kanji/all", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "x",
        "x-rapidapi-key": "x"
    }
})




/** Parse response object
 * returns object parsed from json
 */
const getJsonFromRes = (res) => res.json();

/**  Logs some data. 
 * returns undefined
 */
//const logData = (data) => console.log(data[1].kanji.character);

/** Ignores its data parameter. Attempts to set an element to an uninitialized variable.
 */
const accessKanji = (data) => document.getElementById('kanji').innerHTML = data[1].kanji.character;

// print error to console. returns undefined.
const logError = (err) => console.log(err);

myfetch 
  .then(getJsonFromRes) 
  //.then(logData) 
  .then(accessKanji) 
  .catch(logError);

I want to get a new object (the character object) every time at random. (how I would activate that is another step in my project) 

Any guidance or link to tutorials about this that work well is very much appreciated!! 
Or a an example of course would be ideal.



Aucun commentaire:

Enregistrer un commentaire