我有一个包含 4 列的 SQL:salesman_name |销售|目标|月
目标列每个月都有一个唯一的值,销售额列是该月销售额的总和。
使用 jQuery,我将这些值放入 3 个不同的数组中:
$(resultset).each(function (i, el) {
arraySalesman.push(el.salesman_name);
arraySales.push(el.sales);
arrayGoal.push(el.goal);
});
当我过滤 x 个月的数据集时,我有 x 个销售值和每个销售员的目标 x 值。我需要将这些值减少为每个销售员的唯一销售额和唯一目标值(累积值)。
我在 JavaScript 上尝试过类似的方法:
var dataObjSales = arraySalesman.reduce((t, c, i) => (t[c] = (t[c] || 0) + arraySales[i], t), {});
var dataObjGoal = arraySalesman.reduce((t, c, i) => (t[c] = (t[c] || 0) + arrayGoal[i], t), {});
- 它返回给我类似的东西:
console.log("dataObjSales", dataObjSales);
dataObjSales
{…}
"Salesman1": 1650574.98
"Salesman2": 829888.27
"Salesman3": 1186831.46
"Salesman3": 1342287.91
"Salesman4": 3185057.64
"Salesman5": 387644.28
"Salesman6": 2262157.5
<prototype>: Object { … }
- 我需要将其转换为具有 3 个属性的对象:Obj.salesman、Obj.sales 和 Obj.goals。我可以在第一次减少时这样做吗?或者我可以将这 2 个减少和 salesman_name 数组转换为具有 3 个属性的对象吗?
最佳答案
我相信您可以充分利用 map
:
const arraySalesperson = ["John", "Alice", "Bob", "John", "John", "Alice"];
const arraySales = [100, 420, 138, 89, 74, 86];
const arrayGoals = [1, 2, 3, 4, 5, 6];
// create a map
const resultsBySalesperson = new Map();
// traverse the list of salespersons
for (let i = 0; i < arraySalesperson.length; i++) {
const name = arraySalesperson[i];
// see if it already exists in the map
let salesperson = resultsBySalesperson.get(name);
if (!salesperson) {
// if not, let's create an object now
salesperson = {
name: name,
sales: 0,
goals: 0
};
// store it in the map
resultsBySalesperson.set(name, salesperson);
}
// update the object
salesperson.sales += arraySales[i];
salesperson.goals += arrayGoals[i];
}
// here you have the map ready with both sales and goal properly accumulated
console.info([...resultsBySalesperson.entries()]);
关于javascript - array.reduce( ) 在多个参数上使用索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59058326/