显示来自对象jquery的数据?

时间:2014-10-02 19:59:06

标签: javascript jquery arrays

我有这个

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>";

并且html中的最终结果看起来像这样可以说发票1,计算所有相同的文章 将其所有数量命名,并显示该文章名称的总数量。这是html如何显示它?

<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>

在可口可乐上,我必须显示数量的反值? 我已经为一个工作小提琴做过准备了,但是你可能已经看到我一开始就坚持了下来。

1 个答案:

答案 0 :(得分:2)

这是一种方法

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