使用字符串键在javascript中创建2d对象数组

时间:2014-10-13 15:02:42

标签: javascript arrays javascript-objects

我正在尝试根据订单中的产品为订单创建摘要报告

但是我的摘要数组总是空的。

var summary = [];

_.each(this.products, function(product,counter) {
    var invoice = {};

    invoice.total = 0;
    invoice.dealer_discount = 0;
    invoice.program_discount = 0;
    invoice.adjusted_total = 0;

    _.each(product.materials, function(material) {
        _.each(material.variants, function(variant) {
            var difference = 0;

            invoice.total = parseFloat(invoice.total + variant.price.msrp);

            if(variant.price.discount_type === 'dealer') {
                difference = parseFloat(variant.price.msrp - variant.price.discount_price);

                invoice.dealer_discount = parseFloat(invoice.dealer_discount + difference);
            } else {
                difference = parseFloat(variant.price.msrp - variant.price.discount_price);

                invoice.program_discount = parseFloat(invoice.program_discount + difference);
            }   
        });
    });

    // This never seems to get populated?   
    // If I set the array key to counter like summary[counter] it works fine but I need:    
    summary[product.fulfilled_by] = invoice;
});

我做错了可能很简单。

任何帮助都是适用的。

1 个答案:

答案 0 :(得分:1)

只需更改第一行即可解决您的问题

var summary = {};  // Object

Object以[{1}}方式存储项目,而key : value只包含可由索引访问的值,该索引是数字的,因此当您放置{{1}时}。