I want to change the percentage attribute for each object
I tried using Array.map()
to loop through each object and use a setState(prevState => {return {...prevState, percentage: newValue}})
inside the Array.map()
, But clearly this is incorrect and I don't know how to change the value of this attribute for each object
This is the Array of objects
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
},
])
CodePudding user response:
You have to reduce first to get the total, and then apply the calculation in another loop.
Resource on reducers (to accumulate a total through an array) 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)