I've got a JSON object where I get a product price (number) as a value.
What I want is to convert the price values into strings in the existing object
I use map function:
var prods = [
{
"id": "id-1",
"price": 239000,
"info": "info-1"
},
{
"id": "id-2",
"price": 90770,
"info": "info-2"
},
{
"id": "id-3",
"price": 200787868,
"info": "info-3"
},
];
prods.map(function(a) {
a.price.toString()
.replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 ');
})
I expect the map function to update my prods object, but it stays the same.
(Un)working JS Bin
I wonder, how to update the initial object to the one I need?
Strings are immutable.
String#replace returns a new string and therefore you need an assignment.
And while you only need to change one property, you could use Array#forEach.
var prods = [{ id: "id-1", price: 239000, info: "info-1" }, { id: "id-2", price: 90770, info: "info-2" }, { id: "id-3", price: 200787868, info: "info-3" }];
prods.forEach(function(a) {
a.price = a.price.toString().replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 ');
});
console.log(prods);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You need to assign value back to 'price' after replace
prods.map(function(a) {
a.price = a.price.toString()
.replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 ');
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With