Home > OS >  Printing array length from api fetch in JavaScript
Printing array length from api fetch in JavaScript

Time:12-23

Trying to print total moments owned by a user. But can't get it to work. Want to know how to print length from the returned array. Every time I try to print the array it just display 1, not the users total moments. EDIT.. posted a snippet of json returned from Api just under the code below. the numbers in the [] open up to display more detailed breakdown of each moment.

function MyFunction(e) {
  e.preventDefault();
  var username = document.getElementById("username").value
  document.getElementById("search").innerHTML = username;
  const data = {
    username,
    limit: 3000,
    offset: 0,
    moments,
    rarities: [],
    markers: [],
    onSale: "",
    search: ""
  }

  fetch("https://prod-eternal-backend.onrender.com/api/v1/moment/list", {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      }
    })

    .then(response => {
      return response.json();
    })
    .then(json => {
      console.log(json);
    })
}
{ moments: Array(696), totalMoments: 696 }
moments: Array(696)[0… 99]
  [100… 199]
  [200… 299]
  [300… 399]
  [400… 499]
  [500… 599]
  [600… 695]
length: 696[[Prototype]]: Array(0)
totalMoments: 696[[Prototype]]: Object
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
__proto__: (...)
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

CodePudding user response:

What is coming back from the api is an object so you need to access the property in the object which for you is totalMoment.

console.log(json.totalMoments)

From your response though I would think of removing the totalMoment property from the object and just accessing it by getting the length of the moment property

console.log(json.moments.length)
  • Related