[Ethereum] How to read uint256[] array from a method in a smart contract

solidityweb3js

I'm using this function in my smart contract. It returns an uint256[] array containing the tokens that the user owns.

 /**
   * @dev Returns all of the tokens that the user owns
   * @return An array of token indices
   */
  function myTokens()
    external
    view
    returns (
      uint256[]
    )
  {
    return ownedTokens[msg.sender];
  }

In my web3 js console log, I get the below.

enter image description here

How do I read that array in my js code? Honestly, I don't understand the entire array. I just want to get the token IDs, which it supposed to return.

I'm expecting something like below as shown in Remix.

enter image description here

Here's my web3 js code.

async function retrieveTokenId(contract, walletAddress) {

  await contract.methods.myTokens().call(function(err, res){
        if(!err){
            console.log(res);
        } else {
            console.log(err);
        }
    });

}

Best Answer

Ok, I solved my own problem with the help of https://ethereum.stackexchange.com/users/53608/sanjay-s-b. To display the array, I just need to do the below in my js code.

async function retrieveTokenId(contract, walletAddress) {

    const array = await contract.methods.myTokens().call({
        from: walletAddress
    });

    for (i=0; i < array.length; i++) {
        console.log(array[i]);
    }

    output = JSON.stringify(array, null, 4);
    console.log(output);

}

I could either use a for loop or a JSON.stringify to display the array. Read all about it here, https://medium.com/@timothyrobards/understanding-json-in-javascript-5098876d0915

Related Topic