javascript split array - 进行计算 - 再次合并

时间:2014-09-26 17:53:05

标签: javascript jquery arrays

我有以下数组:

fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]

如何获得相同的数组,但价格价格包含来自amountxprice的值?

最终结果应如下所示:

fruits = [{"fruit":"banana","amount":"2","price":"2"},{"fruit":"apple","amount":"5","price":"10"},{"fruit":"kiwi","amount":"1","price":"5"}]

1 个答案:

答案 0 :(得分:2)

您可以简单地循环数组并进行计算:

for(var i = 0; i < fruits.length; i++) fruits[i].price *= fruits[i].amount;

但请注意,您将丢失原始阵列。

您可能想要添加属性:

for(var i = 0; i < fruits.length; i++)
    fruits[i].finalPrice = fruits[i].price * fruits[i].amount;