1

How can I return an array of child structs of a parent struct?

as an example: After pushing multiple chapters into the parent struct, how can I retrieve all the child structs as an array (or something else suitable)?

contract NewBook {

    struct ChapterData {
        // string chapterID;
        string title;
        uint pages;
    }

    struct BookData {
        // string bookID;
        ChapterData[] chapters;
    }

    mapping(bytes32 => BookData) books; // bookId => BookData

    function addChapter(bytes32 _bookID, string memory title, uint pages) public {
        ChapterData memory c = ChapterData({
            title: title,
            pages: pages
        });
        books[_bookID].chapters.push(c);
    }
0

To do this you'll need to make use of Solidity's experimental ABI encoder, like so:

pragma solidity ^0.5.1;
pragma experimental ABIEncoderV2;
...

You can then create a getter function that returns an array of structs:

function getChapterByBook(bytes32 memory _bookID) 
public 
view 
returns(
    ChapterData[] memory chapters
){
    return books[_bookID].chapters;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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