我想更改每个对象的百分比属性我尝试使用Array.map()
循环通过每个对象,并使用Array.map()
内的setState(prevState => {return {...prevState, percentage: newValue}})
,但显然这是不正确的,我不知道如何改变这个属性的值为每个对象
这是对象数组
interface Data {
state: string;
value: number;
percentage: number;
}
const [data, setData] = useState<Data[]>([
{
state: 'SP',
value: 67836.66,
percentage: 0
},
{
state: 'RJ',
value: 36678.66,
percentage: 0
},
{
state: 'MG',
value: 29229.88,
percentage: 0
},
{
state: 'ES',
value: 27165.48,
percentage: 0
},
{
state: 'Outros',
value: 19849.53,
percentage: 0
},
])
您必须先减少以获得总数,然后在另一个循环中应用计算。
reducer上的资源(通过数组累积总数)https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
const list = [
{
state: 'SP',
value: 67836.66,
percentage: 0
},
{
state: 'RJ',
value: 36678.66,
percentage: 0
},
{
state: 'MG',
value: 29229.88,
percentage: 0
},
{
state: 'ES',
value: 27165.48,
percentage: 0
},
{
state: 'Outros',
value: 19849.53,
percentage: 0
},
]
// Where we compute the total
let total = list.reduce((acc, item) => {
// console.log(acc, item)
return acc += item.value
}, 0)
// Where we apply the percentages (note: map also works)
list.forEach((item) => item.percentage = ((item.value / total) * 100).toFixed(2))
// If you add them up, you get 100 (percent)
console.log(list)