Search code examples
javascriptfor-loopparseint

Change specific name:value pair in Javascript object


I'm trying to simply write a function to convert one of the property values in my JS object to an integer - specifically, convert the weight property for each fruit from string ("200g") to an int (200)

var basket = [
  {
    name: "apple",
    weight: "200g",
    type: "fruit"
  },
  {
    name: "bananas",
    weight: "90g",
    type: "fruit"
  },
   ];

I'd like to write a fnc to convert the weight from str to int and then save the whole thing as a new JS object - new_basket. I'm not quite sure how to structure functions in JS but i have sthing like this:

for(var i=0; i<basket.length; i++) {
    new_basket = parseInt(basket.weight);
    console.log(new_basket)
}

I've seen examples with forEach but they would convert all the properties whilst i just would like all the weights converted. Thanks in advance!


Solution

  • var basket = [
      {
        name: "apple",
        weight: "200g",
        type: "fruit"
      },
      {
        name: "bananas",
        weight: "90g",
        type: "fruit"
      },
       ];
    
    basket.forEach((data,i)=>{
      data['weight']=Number(String(data['weight']).replace('g',''))
    })
    console.log(basket);

    Here you go, hope this helps. if so I'm glad!

    basket.forEach((data,i)=>data['weight']=Number(String(data['weight']).replace('g','')));
    

    in a single line, clean code do the modification to the existing array.