Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  193] [ 2]  / answers: 1 / hits: 25267  / 7 Years ago, tue, january 31, 2017, 12:00:00

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?


More From » arrays

 Answers
5

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; }




[#59131] Monday, January 30, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
piper

Total Points: 734
Total Questions: 93
Total Answers: 112

Location: Burundi
Member since Wed, Apr 6, 2022
2 Years ago
;