Reputation: 39
I am trying to fetch the total number of arrays of validators (example-1038) from JSON file using this code but it is not working.
What is wrong with my code?
let fetchRes = fetch("https://avax.dev/data/validators.json");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes
.then(res => res.json())
.then(d => {
console.log(d)
let len = Object.keys(validators).length;
console.log(len);
});
Upvotes: 0
Views: 95
Reputation: 179
In your code, "d" is an object. Inside the object "validators" is a key with array as value (key: value pair). So in order to access the validators length you will have to do "d.validators.length".
let fetchRes = fetch("https://avax.dev/data/validators.json");
fetchRes.then(res => res.json())
.then(d => {
console.log(d);
//get the array length using d.validators.length
console.log(d.validators.length)
})
Upvotes: 1
Reputation: 898
I formatted the code too.
You were trying to access the validators
array outside .then
. So the data (d
) we get back is what I am using to get the validators
.
let fetchRes = fetch("https://avax.dev/data/validators.json");
// fetchRes is the promise to resolve
// it by using.then() method
fetchRes
.then((res) => res.json())
.then((d) => {
console.log(d);
let len = d.validators.length;
console.log(len);
});
Upvotes: 0
Reputation: 433
You currently are trying to get the length of the validators field outside the promise resolution. What is actually happening is that these lines
var len = Object.keys(validators).length;
console.log(len);
run before the console.log(d)
. On top of this the variable d
is not available outside of the .then()
to fix this just move the code inside the .then()
fetchRes
.then(res => res.json())
.then(d => {
const length = d.validators.length;
console.log(length);
})
Upvotes: 0