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

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) 
    ChapterData[] memory chapters
    return books[_bookID].chapters;

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.