Javascript进行计算和过滤列表



我有下面的数组-

const data=[
{
month:"nov",
veryLate:3,
Late:5,
onTime:2
},
{
month:"dec",
veryLate:1,
Late:3,
onTime:16
},
{
month:"jan",
veryLate:28,
Late:1,
onTime:1
},
}

我想对这个数组进行过滤和计算,以便获得百分比。

。veryLate + Late+ onTime = (3+5+2) = 10

所以百分比是-

const data= [
{
month:"nov",
veryLate:30,
Late:50,
onTime:20
},
{
month:"dec",
veryLate:5,
Late:15,
onTime:80
},
,
{
month:"jan",
veryLate:98.33,
Late:3.33,
onTime:3.33
},]

为了计算这个值,我执行了下面的操作,但是在括号中出现了语法错误-

var filteredData=data.map(x=>{
x.month,
x.veryLate/(x.veryLate+x.Late+x.onTime)*100,
x.Late/(x.veryLate+x.Late+x.onTime)*100,
x.onTime/(x.veryLate+x.Late+x.onTime)*100,
});

如何获得计算结果?

veryLate在x中不起作用,它应该是veryLate本身,其他

const data=[
{
month:"nov",
veryLate:3,
Late:5,
onTime:2
},
{
month:"dec",
veryLate:1,
Late:3,
onTime:16
},
{
month:"jan",
veryLate:28,
Late:1,
onTime:1
},
]
var filteredData= data.map(x => (
{
...x, 
veryLate:  x.veryLate/(x.veryLate+x.Late+x.onTime)*100,         
Late: x.Late/(x.veryLate+x.Late+x.onTime)*100, 
onTime: x.onTime/(x.veryLate+x.Late+x.onTime)*100
})
)
console.log(filteredData)

还必须将返回的对象字面值包装到括号中。当前,花括号被表示为函数体。

map()方法需要返回一个值

试试这个

var filteredData=data.map(x => {
// get the original values to avoid repeating x. 
const {month, veryLate, Late, onTime} = x;

// do your calculations
const newVeryLate = veryLate / ( veryLate + Late + onTime) * 100;
const newLate = Late / (veryLate + Late + onTime) * 100;
const newOnTime = onTime / (veryLate + Late + onTime) * 100;

// return the new object
return {month, veryLate: newVeryLate, Late: newLate, onTime: newOnTime}
});

var filteredData=data.reduce((a, v)=>{
let obj = {};
let sum = v.veryLate+v.Late+v.onTime;
obj.month = v.month;
obj.veryLate = v.veryLate/sum*100;
obj.Late = v.Late/sum*100;
obj.onTime = v.onTime/sum*100;
a.push(obj)
return a;
}, []);

抛出错误因为:

  1. 数据数组没有右括号
  2. map方法没有返回任何东西。如果你想从它返回一个对象,使用return关键字。

问题是传递给Array.prototype.map的回调需要在每次迭代中返回一些东西,而在您当前的实现中您没有返回任何东西

您可以如下所示使用map:

const data = [
{ month: "nov", veryLate: 3, Late: 5, onTime: 2 },
{ month: "dec", veryLate: 1, Late: 3, onTime: 16 },
{ month: "jan", veryLate: 28, Late: 1, onTime: 1 },
];
const filteredData = data.map(({ month, veryLate, Late, onTime }) => {
const total = veryLate + Late + onTime;
return {
month,
veryLate: (veryLate / total) * 100,
Late: (Late / total) * 100,
onTime: (onTime / total) * 100,
};
});
console.log(filteredData);

如果你发现map令人困惑,你也可以用常规的for循环来做,如下所示:

const data = [
{ month: "nov", veryLate: 3, Late: 5, onTime: 2 },
{ month: "dec", veryLate: 1, Late: 3, onTime: 16 },
{ month: "jan", veryLate: 28, Late: 1, onTime: 1 },
];
const filteredData = [];
for (let i = 0; i < data.length; i++) {
const { month, veryLate, Late, onTime } = data[i];
const total = veryLate + Late + onTime;
result.push({
month,
veryLate: (veryLate / total) * 100,
Late: (Late / total) * 100,
onTime: (onTime / total) * 100,
});
}
console.log(filteredData);

附加文档:

  • 对象Destructuring

最新更新