Javascript 减少对象数组中的某些对象
Javascript reduce for certain objects within an array of objects
我在计算对象值数组时遇到了一个小问题...我下面的代码工作得很好但是如果我只想定位 reduce 函数中的某些对象怎么办?
基本上,类似于 SQL WHERE 函数,所以
newcost = Number((cart.map(item => (item.cost * item.amm)).reduce((prev, next) => Number(prev) + Number(next))).toFixed(2));
会是
newcost = Number((cart.map(item => (item.cost * item.amm)).reduce((prev, next) => Number(prev) + Number(next))).toFixed(2)) WHERE item.type === "c";
你知道,类似于此。我怎样才能实现这样的目标?
谢谢。
以下是使用 filter()
的方法。 filter()
returns 函数传递给它的数组 returns true。这具有仅重新调整类型 'c' 的项目的效果。
var cart = [
{type:'c', cost:20.00, amm: 10},
{type:'d', cost:20.00, amm: 1},
{type:'d', cost:20.00, amm: 2},
{type:'c', cost:1.00, amm: 5},
{type:'a', cost:20.00, amm: 7},
]
let newcost = cart.filter(i => i.type === 'c') // only c type items
.map(item => item.cost * item.amm)
.reduce((prev, next) => prev + next)
.toFixed(2);
console.log(newcost)
此外,您没有询问,但 map()
调用是无关紧要的 — 您并不真正需要它,它会导致数据额外循环(您也可以只在 reduce()
并省略 filter()
尽管这可能会开始影响可读性):
var cart = [
{type:'c', cost:20.00, amm: 10},
{type:'d', cost:20.00, amm: 1},
{type:'d', cost:20.00, amm: 2},
{type:'c', cost:1.00, amm: 5},
{type:'a', cost:20.00, amm: 7},
]
let newcost = cart.filter(i => i.type === 'c')
.reduce((prev, next) => prev + next.cost * next.amm, 0)
.toFixed(2);
console.log(newcost)
首先在 reduce 函数中添加您的条件。如果该元素与您的条件不匹配,则先 return 累加器而不修改它。
我在计算对象值数组时遇到了一个小问题...我下面的代码工作得很好但是如果我只想定位 reduce 函数中的某些对象怎么办?
基本上,类似于 SQL WHERE 函数,所以
newcost = Number((cart.map(item => (item.cost * item.amm)).reduce((prev, next) => Number(prev) + Number(next))).toFixed(2));
会是
newcost = Number((cart.map(item => (item.cost * item.amm)).reduce((prev, next) => Number(prev) + Number(next))).toFixed(2)) WHERE item.type === "c";
你知道,类似于此。我怎样才能实现这样的目标?
谢谢。
以下是使用 filter()
的方法。 filter()
returns 函数传递给它的数组 returns true。这具有仅重新调整类型 'c' 的项目的效果。
var cart = [
{type:'c', cost:20.00, amm: 10},
{type:'d', cost:20.00, amm: 1},
{type:'d', cost:20.00, amm: 2},
{type:'c', cost:1.00, amm: 5},
{type:'a', cost:20.00, amm: 7},
]
let newcost = cart.filter(i => i.type === 'c') // only c type items
.map(item => item.cost * item.amm)
.reduce((prev, next) => prev + next)
.toFixed(2);
console.log(newcost)
此外,您没有询问,但 map()
调用是无关紧要的 — 您并不真正需要它,它会导致数据额外循环(您也可以只在 reduce()
并省略 filter()
尽管这可能会开始影响可读性):
var cart = [
{type:'c', cost:20.00, amm: 10},
{type:'d', cost:20.00, amm: 1},
{type:'d', cost:20.00, amm: 2},
{type:'c', cost:1.00, amm: 5},
{type:'a', cost:20.00, amm: 7},
]
let newcost = cart.filter(i => i.type === 'c')
.reduce((prev, next) => prev + next.cost * next.amm, 0)
.toFixed(2);
console.log(newcost)
首先在 reduce 函数中添加您的条件。如果该元素与您的条件不匹配,则先 return 累加器而不修改它。