I need to amend the amount to add £ before the number and change it to two decimals i.e. £9.00
const data = [
{
title: 'Todo',
amount: 9.99,
},
{
title: 'In-Progress',
amount: 4,
},
{
title: 'Completed',
amount: 10,
},
{
title: 'Short',
amount: 15.48,
},
];
I can’t work out how?
>Solution :
You can use .map()
and .toFixed(2)
to achieve this:
const updatedData = data.map(item => {
return {
title: item.title,
amount: '£' + item.amount.toFixed(2),
};
});
item.amount.toFixed(2)
will return the amount as a string with two decimal places. The '£' +
part will add the pound sign before the amount.
Shorter Way :
const updatedData = data.map(({title, amount}) => ({
title,
amount: `£${amount.toFixed(2)}`
}));
If each object in the data array has several properties, use the spread operator like this :
const updatedData = data.map(({amount, ...rest}) => ({
amount: `£${amount.toFixed(2)}`,
...rest
}));