0

I have a JSON Data like this :

<script>
    var data_work_in =[
             {"ID":13,"share":36,"CQty":0,"CPrice": 1},
             {"ID":14,"share":36,"CQty":0,"CPrice": 1}
    ]
data_work_in.CQty = data_work_in.ClipQty%
</script>

I want to rename the headers of my JSON for CQty to be ClipQty%.

Please help

  • 1
    actually that's a JavaScript object, it's not JSON. JSON is text. – ADyson Nov 06 '18 at 15:45
  • 2
    Possible duplicate of [JavaScript: Object Rename Key](https://stackoverflow.com/questions/4647817/javascript-object-rename-key) – ADyson Nov 06 '18 at 15:46
  • 1
    Although it's not very difficult to do, you might want to first double check is it something you want to do. Currently you can access these by doing -> `data_work_in[0].CQty` , but after renaming you would have to do -> `data_work_in[0]["ClipQty%"]` And that's just not as nice.. :) – Keith Nov 06 '18 at 15:56

3 Answers3

0

You will need to iterate all elements are the columns are not linked You can create new column,assign value then delete exisitng column like this

 var data_work_in =[
             {"ID":13,"share":36,"CQty":0,"CPrice": 1},
             {"ID":14,"share":36,"CQty":0,"CPrice": 1}
    ];
data_work_in.forEach(e=>{
e["ClipQty%"]=e['CQty'];delete e["CQty"];
})
console.log(data_work_in)
Abhishek Mathur
  • 478
  • 5
  • 12
0

Instead of mutating the original array use map to create a new array with desired keys and value

let orgArray = [{
    "ID": 13,
    "share": 36,
    "CQty": 0,
    "CPrice": 1
  },
  {
    "ID": 14,
    "share": 36,
    "CQty": 0,
    "CPrice": 1
  }
]
let newArray = orgArray.map(function(item) {
  return Object.assign({}, {
    "ID": item.ID,
    "share": item.ID,
    "ClipQty%": item.ID,
    "CPrice": item.ID
  })
})
console.log(newArray)
brk
  • 48,835
  • 10
  • 56
  • 78
0

You can't replace, you will have to add a new key, assign the value to it, then delete the original key.

This should work on most (non IE) browsers:

var data_work_in =[
    {"ID":13,"share":36,"CQty":0,"CPrice": 1},
    {"ID":14,"share":36,"CQty":0,"CPrice": 1}
];

Array.prototype.forEach.call(data_work_in, function(it){
    if(it.hasOwnProperty("CQty")){
        it["ClipQty"] = it.CQty;
        delete it["CQty"]
    }
});
Asinus Rex
  • 535
  • 9
  • 29