javascript - 如何从对象数组中删除一个值?
问题描述
我有一个返回对象数组的函数,我希望数据数组返回像这样的“数据”:[5466, 25],pointsExchanged 和 pointsExpired 返回一个像这样的对象数组:[ { sum: '5466' } ]
export const getPieChart = async () => {
const [pointsExchanged, pointsExpired] = await Promise.all([
conn("statements")
.sum("value")
.where('type', 'deposito'),
conn("statements")
.sum("value")
.where('type', 'exchange'),
]);
return {
labels: ['Pontos trocados', 'Pontos expirados', 'Pontos atribuidos'],
datasets: [
{
backgroundColor: ["blue", 'red'],
data: [pointsExchanged, pointsExpired]
},
]
};
}
函数响应:
{
"labels": [
"Pontos trocados",
"Pontos expirados",
"Pontos atribuidos"
],
"datasets": [
{
"backgroundColor": [
"blue",
"red"
],
"data": [
[
{
"sum": "5466"
}
],
[
{
"sum": "25"
}
]
]
}
] }
我希望如何回应:
{
"labels": [
"Pontos trocados",
"Pontos expirados",
"Pontos atribuidos"
],
"datasets": [
{
"backgroundColor": [
"blue",
"red"
],
"data": [5466, 25],
}
] }
解决方案
只需映射它们并提取sum
属性,然后使用扩展运算符将它们合并...
data: [
...pointsExchanged.map(point => Number(point.sum)),
...pointsExpired.map(point => Number(point.sum))
]
const pointsExchanged = [{"sum": "5466"}];
const pointsExpired = [{"sum": "25"}];
const data = [
...pointsExchanged.map(point => Number(point.sum)),
...pointsExpired.map(point => Number(point.sum))
];
console.log(data)