从下面的代码中,我想基于我的输入值/过滤器获得总计的值。如果我使用.filter()
方法,则无法在我的应用程序(getting empty response or 0
)中运行,但是在外部独立页面中运行,我不确定为什么。请帮我。谢谢。
使用以下代码,我在我的应用程序中遇到错误:TypeError: Cannot read property 'reduce' of undefined at getTotal()
index.js:
function getTotal(data, filters) {
console.log(JSON.stringify(filters));//{"Name":"ABC","Dept":"First","FY":"2016","Quarter":"1","Month":"April"}
console.log(JSON.stringify(data));//[{"Name":"ABC","Dept":"First","FY":"2016","Quarter":"1","Month":"April","Total":"1200"},{"Name":"ABC","Dept":"Second","FY":"2017","Quarter":"2","Month":"May","Total":"200"},{"Name":"ABC","Dept":"First","FY":"2016","Quarter":"1","Month":"June","Total":"150"},{"Name":"DEF","Dept":"First","FY":"2016","Quarter":"1","Month":"April","Total":"200"},{"Name":"DEF","Dept":"Second","FY":"2017","Quarter":"2","Month":"May","Total":"100"},{"Name":"DEF","Dept":"First","FY":"2016","Quarter":"1","Month":"June","Total":"500"}]
var f = Object.entries(filters);
console.log("f is: "+f);// Name,ABC,Dept,First,FY,2016,Quarter,1,Month,April
const test = data.find(o => f.every(([k, v]) => o[k] === v)).reduce((s, { Total }) => s + +Total, 0);
return test;//Output should be: 100
}
var data = [{ Name: "ABC", Dept: "First", FY: "2016", Quarter: "1", Month: "April", Total: "100" }, { Name: "ABC", Dept: "Second", FY: "2017", Quarter: "2", Month: "May", Total: "200" }, { Name: "ABC", Dept: "First", FY: "2016", Quarter: "1", Month: "June", Total: "150" }, { Name: "DEF", Dept: "First", FY: "2016", Quarter: "1", Month: "April", Total: "200" }, { Name: "DEF", Dept: "Second", FY: "2017", Quarter: "2", Month: "May", Total: "100" }, { Name: "DEF", Dept: "First", FY: "2016", Quarter: "1", Month: "June", Total: "500" }];
console.log(getTotal(data, { Name: 'ABC', Dept: 'First', FY: '2016', Quarter: '1', Month: 'April' })); // shoud give: 100
是的,现在得到的答案是:https://github.com/flutter/flutter/wiki/Add-Flutter-to-existing-apps
答案 0 :(得分:2)
您应该使用Array.prototype.filter
而不是Array.prototype.find
,因为它会返回 array 而不是数组中的单个对象。
对象没有reduce
方法数组,但是:
function getTotal(data, filters) {
var f = Object.entries(filters);
const test = data.filter(o => f.every(([k, v]) => o[k] === v)).reduce((s, { Total }) => s + +Total, 0);
return test;//Output should be: 100
}
var data = [{ Name: "ABC", Dept: "First", FY: "2016", Quarter: "1", Month: "April", Total: "100" }, { Name: "ABC", Dept: "Second", FY: "2017", Quarter: "2", Month: "May", Total: "200" }, { Name: "ABC", Dept: "First", FY: "2016", Quarter: "1", Month: "June", Total: "150" }, { Name: "DEF", Dept: "First", FY: "2016", Quarter: "1", Month: "April", Total: "200" }, { Name: "DEF", Dept: "Second", FY: "2017", Quarter: "2", Month: "May", Total: "100" }, { Name: "DEF", Dept: "First", FY: "2016", Quarter: "1", Month: "June", Total: "500" }];
console.log(getTotal(data, { Name: 'ABC', Dept: 'First', FY: '2016', Quarter: '1', Month: 'April' })); // shoud give: 100