我有以下数组:
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"}]
答案 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;