Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Display data from object jquery?

I have this

JS

var invoice = 1;

var orders = [
    [{
        "invoice": "1",
        "article": "Coca Cola",
        "qty": "5",
        "active": "Yes"
    }, {
        "invoice": "1",
        "article": "Fanta",
        "qty": "10",
        "active": "Yes"
    }, {
        "invoice": "1",
        "article": "Sprite",
        "qty": "40",
        "active": "Yes"
    },{
        "invoice": "1",
        "article": "Coca Cola",
        "qty": "40",
        "active": "Yes"
    }],
    [{
        "invoice": "2",
        "article": "Coca Cola",
        "qty": "55",
        "active": "Yes"
    }, {
        "invoice": "2",
        "article": "Fanta",
        "qty": "10",
        "active": "Yes"
    }]
];

var msg = "<div id=results>" + results + "</div>";

and final results in html to look like this lets say for invoice 1, to count all articles with same name all its qty, and display that article name with total amount of the qty. Here is html how it need to be display?

<div id="results">
<div class="each">
<input value="Coca Cola"><input value="45">
</div>
<div class="each">
<input value="Fanta"><input value="10">
</div>
<div class="each">
<input value="Sprite"><input value="40">
</div>

On Coca Cola i have to display countet values of qty? I have starded a working fiddle, but as you may see i have stucked at start.

Upvotes: 0

Views: 93

Answers (1)

adeneo
adeneo

Reputation: 318252

Here's one way to do it

function getInvoice(numb) {
    return $('<section />', {
        'class' : 'results'
    }).append(
        $.map(orders, function(arr) {
            var o = {};
            $.each(arr, function(_, obj) {
                if (obj.invoice == numb)
                    o[obj.article] = (o[obj.article] || 0) + (+obj.qty);
            });

            return $.map(o, function(qty, article) {
                return $('<div />', {
                    'class' : 'each'
                }).append(
                    $('<input />', {value : article}),
                    $('<input />', {value : qty})
                ).get(0);
            });
        })
    );
}

FIDDLE

Upvotes: 2

Related Questions