Home > OS >  how to add an object in json array with different name but same value
how to add an object in json array with different name but same value

Time:01-18

I am creating a chart right now I am facing an issue I have a json array with certain value, so below I have an element stock_change_p(can be positive or negative) what I want is to add a new element with same value (but positive) in the whole json array.

This is my array now

let data ={
    "status": "success",
    "data": [
        {
            "sector_code": "0801",
            "stocks": [
                {                    
                       
                    "stock_change_p": "-1.34", 
                },
                {                  
                                    
                    "stock_change_p": "0.96",                  
                },
                {                 
                   
                    "stock_change_p": "-0.24",                
                }
            ]
        },
        
    ]
}

What I want my array to look later

let data ={
    "status": "success",
    "data": [
        {
            "sector_code": "0801",
            "stocks": [
                {                    
                    "size": "1.34",     
                    "stock_change_p": "-1.34", 
                },
                {                  
                    "size": "0.96",                    
                    "stock_change_p": "0.96",                  
                },
                {                 
                    "size": "0.24",
                    "stock_change_p": "-0.24",                
                }
            ]
        },
        
    ]
}

CodePudding user response:

Using Math.abs() negative values to positive

Try this code it's help you

 let data = {
      "status": "success",
      "data": [... ]
    }

    for (let i = 0; i < data.data.length; i  ) {

      let stocks = data.data[i].stocks;
      for (let j = 0; j < stocks.length; j  ) {

        let obj = stocks[j];
        obj['size'] = Math.abs(obj.stock_change_p);
      }
    }
    console.log(data, 'data');

CodePudding user response:

An alternative way to achieve the same result is provided below

let data = {
  "status": "success",
  "data": [{
      "sector_code": "0801",
      "stocks": [{

          "stock_change_p": "-1.34",
        },
        {

          "stock_change_p": "0.96",
        },
        {

          "stock_change_p": "-0.24",
        }
      ]
    },

  ]
};

const addSize = (dataObj = data) => ({
  ...dataObj,
  data: [...dataObj.data.map(d => ({
    ...d,
    stocks: d.stocks.map(s => ({
      ...s,
      size: Math.abs(parseFloat(s.stock_change_p)).toString()
    }))
  }))]
});

console.log(addSize());

  •  Tags:  
  • Related