Change value in JSON array and return updated array JS

21,798

Solution 1

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

Solution 2

you need to use this one

Sample Code

prods.map(function(a) {
             a.price = ""+a.price;
})

Solution 3

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

Solution 4

Note that map apply a function to each element on array, you could return new array, it won't modify existing array, so you need assign new array to some variable.

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 = prods.map(function(a) {
  a.price = a.price.toString()
   .replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 ');
  return a;
});
console.log(prods);

Share:
21,798
Alexandr Belov
Author by

Alexandr Belov

Updated on July 09, 2022

Comments

  • Alexandr Belov
    Alexandr Belov almost 2 years

    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?