2

So I have this simple smart contract:

pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;

contract People {
    struct Person {
        string name;
        uint age;
        string[] hobbies;
    }
    
    Person[] people;

    function addPeople(Person[] memory _people) public {
        for(uint i=0; i<_people.length; i++) {
            people.push(Person(_people[i].name, _people[i].age, _people[i].hobbies));
        }
    }

    function getPeople() public view returns (Person[] memory) {
        return people;
    }

I deploy it to Remix and try to add the following information in "people":

[["alice",5, ["a","b"]],["bob",6,["c","d"]]]

The transaction goes through just fine, however when I try to read a member of the people array, only the name and age get returned, the hobbies arrays don't, like so:

enter image description here

I have tried so many different ways to populate the array, I've tried to put it in a mapping and I always get the same result - the array, no matter the data type, doesn't get stored/returned. What is the solution here?

1 Answer 1

1

Remix only displays the first level of nested structures by default. In other words, if you have an array of structs and each struct contains an array or a mapping, only the top-level array of structs will be displayed in Remix by default. However, the data is still correctly stored on the blockchain. To view the entire Person struct (including the hobbies array), you can create a view function to access the array:

function getOnePeople(uint _index) public view returns (Person memory){
        return people[_index];
    }

Then you can retrive all the desired data in Remix:

enter image description here

Hope it helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.