gpt4 book ai didi

javascript - 在循环中获取属性的 sum() 而不循环遍历该对象的所有实例

转载 作者:行者123 更新时间:2023-12-03 08:46:05 26 4
gpt4 key购买 nike

我有一个模型 DummyModel,它具有属性 attOneattTwoattThree

要获取 attOne 的所有实例,可以使用 -

DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} });

上面的查询或多或少对应于 MySQL 查询 -

select attOne from DummyModel where attTwo = 'someValue'

但是,我需要找到从上述查询返回的所有 attOne 值的总和。也就是说,MySQL 相当于 -

select sum(attOne) from DummyModel where attTwo = 'someValue'

我读到环回不支持聚合函数(即groupby)。但是有没有办法得到sum(attOne)

我知道一种方法是获取对象,然后循环所有实例并添加它。

我想知道是否有任何预先存在的环回方法可以执行相同的操作。

最佳答案

假设这段代码

f = DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} });

返回一个像这样的数组

[
{attTwo: 'someValue' ,attOne: 1}
{attTwo: 'otherValue',attOne: 1}
]

您可以使用reduce function将函数应用于所有元素

var sum = f.reduce(function(last, d) {return d.attOne + last},0);

这是工作代码

DummyModel = {
find: function(a) {
return [{
attTwo: 'someValue',
attOne: 1
}, {
attTwo: 'otherValue',
attOne: 2
}];
}
}

f = DummyModel.find({
where: {
attTwo: 'someValue'
},
fields: {
attOne: true
}
});

sum = f.reduce(function(last, d) {
return d.attOne + last;
}, 0);

alert(sum);

关于javascript - 在循环中获取属性的 sum() 而不循环遍历该对象的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32881904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com