Purchasedata.find(function(err, purchasedatas) {
    if (err) {
        return handleError(res, err);
    }

    var totalprice = 0;
    for (var i = 0; i < purchasedatas.length; i++) {
        findProduct(i, function(i, price) {
        });
    }

    function findProduct(i, callback) {

        Productpointallocation.find({
            'productcode': purchasedatas[i].ItemCode
        }).exec(function(err, productpointallocations) {

            if (err) {
                return handleError(res, err);
            }

            var pointMultiplier = 0;
            if (!productpointallocations) {
                pointMultiplier = 0;
            } else if (productpointallocations.length == 0) {

                pointMultiplier = 0;

            }

            if (pointMultiplier >= 0) {

                var totalprice = (parseFloat(purchasedatas[i].ItemCost.value)) / 10 * pointMultiplier;
			   purchasedatas.push({price:totalprice,productname:productpointallocations[0].productname});


			   console.log(purchasedatas);

            }

        });
    }
});





在purchadata中,我得到两个对象

[ { _id: 592fbd65304a7315f87d3f40,
    ItemCode: '10',
    PurchaseQuantity: 3,
    ItemCost: 15,
   },
  { _id: 592fbd65304a7315f87d3f3f,
    ItemCode: '6',
    PurchaseQuantity: 1,
    ItemCost: 5,
    }]


基于ItemCode我正在计算价格。在计算价格后,我想将价格和产品名称推入Purchaseatas对象

purchasedatas.push({price:totalprice,productname:productpointallocations[0].productname});


我写了上面的代码,但我得到这样的对象

[ { _id: 592fbd65304a7315f87d3f40,
    ItemCode: '10',
    PurchaseQuantity: 3,
    ItemCost: 15,
   },
  { _id: 592fbd65304a7315f87d3f3f,
    ItemCode: '6',
    PurchaseQuantity: 1,
    ItemCost: 5,
    },
  { price: 4.5, productname: ' ADAPTER-PCS' } ]
[ { _id: 592fbd65304a7315f87d3f40,
    ItemCode: '10',
    PurchaseQuantity: 3,
    ItemCost: 15,
    },
  { _id: 592fbd65304a7315f87d3f3f,
    ItemCode: '6',
    PurchaseQuantity: 1,
    ItemCost: 5,
    },
  { price: 4.5, productname: 'ADAPTER-PCS' },
  { price: 1, productname: 'UNIVERSAL AC DC ' } ]


推高价格和产品名称后的预期结果

[ { _id: 592fbd65304a7315f87d3f40,
    ItemCode: '10',
    PurchaseQuantity: 3,
    ItemCost: 15,
    price: 4.5,
    productname: 'ADAPTER-PCS'
   },
  { _id: 592fbd65304a7315f87d3f3f,
    ItemCode: '6',
    PurchaseQuantity: 1,
    ItemCost: 5,
    price: 1,
    'productname: 'UNIVERSAL AC DC '
    }]

最佳答案

Javascript的Array.push()函数会将对象附加到数组。如果要向数组中已有的元素添加属性,则必须修改对象。为此,您需要在数组中找到对象的索引,例如,通过循环遍历并比较ID。

如果要修改数组内部的所有对象,也可以使用Array.map()

10-06 04:21
查看更多