JSON Examples

9- Processing Object Data

Output

JS

function Book(title, author, inStock, price) {
    this.title = title;
    this.author = author;
    this.inStock = inStock;
    this.price = price;
}

Book.prototype.getTitle = function() {
    return this.title;
}

Book.prototype.getAuthor = function() {
    return this.author;
}

Book.prototype.getInStock = function() {
    return this.inStock;
}

Book.prototype.getPrice = function() {
    return this.firstName + ' ' + this.lastName;
}

HTML

<script>
    let info  = document.getElementById('info'),
        br    = '<br>',
        html  = '<span class="spacer">Books in stock:' + br + '</span>',
        books = [
            new Book('Stranger in a Strange Land', 'Heinlein', true, 10.99),
            new Book('Fellowship of the Ring', 'Tolkien', true, 5.99),
            new Book('The Two Towers', 'Tolkien', false, 5.99),
            new Book('The Return of the King', 'Tolkien', true, 6.99),
            new Book('A Spell for Chamelion', 'Anthony', true, 6.99),
            new Book('The Source of Magic', 'Anthony', false, 8.99),
            new Book('Starship Troopers', 'Heinlein', true, 8.99),
            new Book('Dune', 'Herbert', false, 12.99),
            new Book('Children of Dune', 'Herbert', true, 10.99)
        ];
    // get all books that are in stock
    for(var i = 0; i < books.length; i++) {
        if (books[i].getInStock()) {
            html += "&nbsp;&nbsp- " + books[i].getTitle() + br;
        }
    }
    
    html += '<span class="spacer">' +
                'Books &gt; $7.00:' +
            '</span><br>';
            
    // get books that cost more than $7.00
    for(var i = 0; i < books.length; i++) {
        if(books[i].getPrice() > 7.00) {
            html += '&nbsp;&nbsp;- ' + books[i].getTitle() + ' ($' + 
                    books[i].getPrice().toFixed(2) + ')' + br; 
        }
    }

    info.innerHTML = html;
</script>