Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Amend an object in an array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading