Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value in JSON array and return updated array JS

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?

like image 878
Alexandr Belov Avatar asked Sep 20 '26 00:09

Alexandr Belov


2 Answers

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; }
like image 154
Nina Scholz Avatar answered Sep 21 '26 14:09

Nina Scholz


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 ');
})
like image 28
Victor Leontyev Avatar answered Sep 21 '26 13:09

Victor Leontyev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!