0

Exchange comma with dot in an object item on an array

let array=[
{price: "149,99",rating: "4.9"},
{price: "49,99",rating: "4.2"}

];

How i can replace comma in the value of price with dot and return an array with updated price value

I tried to replace dot using map method but i can't return all array

let arrayApdated= array.map(item=>item.replace(/,/g,'.');

// return ["149.99","49.99"];
// expecting value [{price: "149,99",rating: "4.9"},{price: "49,99",rating: "4.2"}];
ksyDev
  • 1
  • try using `replace()` method. https://www.w3schools.com/jsref/jsref_replace.asp Loop thru the array and do something like `array[i].price.replace(',', '.')` – Abhishek Sharma May 08 '21 at 20:07

5 Answers5

0

Map the array, get the property you wish to replace, and the rest of the object using destructuring with rest, and then create a new object by replacing the string, and spreading the rest of the object:

const array=[{price: "149,99",rating: "4.9"},{price: "49,99",rating: "4.2"}];

const result = array.map(({ price, ...rest }) => ({
  price: price.replace(',', '.'),
  ...rest
}));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

as a solution

let array=[
  {price: "149,99",rating: "4.9"},
  {price: "49,99",rating: "4.2"}
];

array = array.map(item =>{
  for(let field in item){
    item[field] = item[field].replace(',', '.')
  }
  return item;
})

//[{price: "149.99", rating: "4.9"},{price: "49.99", rating: "4.2"}]
Allure
  • 513
  • 2
  • 12
0
let array = [
  { price: "149,99", rating: "4.9" },
  { price: "49,99", rating: "4.2" },
];
for (let i = 0; i < array.length; i++)
  array[i].price = array[i].price.replace(",", ".");

console.log(JSON.stringify(array));
Daniel Bellmas
  • 589
  • 5
  • 17
0

You can use the map function to convert the objects one at a time

let array=[
    {price: "149,99",rating: "4.9"},
    {price: "49,99",rating: "4.2"}    
];
let result = array.map(value=> 
{return {price:value.price.replace(',','.'), rating:value.rating};});
Manuel
  • 157
  • 1
  • 10
0

let array = [
    {price: "149,99", rating: "4.9"},
    {price: "49,99", rating: "4.2"}
];

array.map(item => {
    console.log(`${item.price.replace(',', '.')}, ${item.rating}`);
})
David Öztürk
  • 3,434
  • 1
  • 4
  • 7