0

How can I push a struct instance into a mapping which contains a distinct struct which contains a struct array of the attempted struct instance type?

Example:

contract NewBook {

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

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

    mapping(string => BookData) public books;

    //This is where the problem occurs, how do I add a struct instance 
    //into a struct containing an array of the struct that I'm trying to add?
    function addChapter(string memory _bookID, string memory _chapterID) public {
        books[_bookID].chapters.push(ChapterData[_chapterID]);
    }
}
1

Try this:

pragma solidity 0.5.1;

contract NewBook {

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

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

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

    //This is where the problem occurs, how do I add a struct instance 
    //into a struct containing an array of the struct that I'm trying to add?
    function addChapter(bytes32 _bookID, string memory title, uint pages) public {
        ChapterData memory c = ChapterData({
            title: title,
            pages: pages
        });
        books[_bookID].chapters.push(c);
    }

    function getBookChapter(bytes32 bookId, uint chapter) public view returns(string memory title, uint pages) {
        BookData storage b = books[bookId];
        ChapterData storage c = b.chapters[chapter];
        return(c.title, c.pages);
    }
}

This isn't the ideal or complete organization, but hopefully clears up the question raised.

Hope it helps.

| improve this answer | |
  • How would you view the specific chapter data if you mind Rob? – NowsyMe Jul 12 '19 at 23:27
  • I'll revise the answer. – Rob Hitchens Jul 12 '19 at 23:47
  • thank you :D you're way more useful than my university! – NowsyMe Jul 13 '19 at 0:10

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.