to replace a key with a given key in an Array of Objects

by Ishank Dubey

JavaScript

var anArray = 
[
  {
    
    "type": "test",
    "xyz": [
      {
        "id": "55",
        "label": "testLabel",
        "type": "testLine",
        "xyz": [
          {
            "id": "12",
            "label": "testLabel",
            "type": "testUnit"
          },
          {
            "id": "399",
            "label": "Unit [399]",
            "type": "Unit"
          },
          {
            "id": "400",
            "label": "Unit [400]",
            "type": "Unit"
          },
          {
            "id": "401",
            "label": "Unit [401]",
            "type": "Unit"
          },
          {
            "id": "402",
            "label": "Unit [402]",
            "type": "Unit"
          },
          {
            "id": "403",
            "label": "Unit [403]",
            "type": "Unit"
          },
          {
            "id": "404",
            "label": "Unit [404]",
            "type": "Unit"
          },
          {
            "id": "405",
            "label": "Unit [405]",
            "type": "Unit"
          },
          {
            "id": "494",
            "label": "Unit [494]",
            "type": "Unit"
          },
          {
            "id": "687",
            "label": "Unit [687]",
            "type": "Unit"
          },
          {
            "id": "688",
            "label": "Unit [688]",
            "type": "Unit"
          },
          {
            "id": "841",
            "label": "Unit [841]",
            "type": "Unit"
          },
          {
            "id": "842",
            "label": "Unit [842]",
            "type": "Unit"
          }
        ]
      }
                ]
}
]
replaceKey(anArray,'xyz', 'children1');
function replaceKey(anArray, aKey, newKey){
var anIndex, aKeyArray, anObj;
for(anIndex in anArray){
     if(anArray.hasOwnProperty(anIndex)){
       anObj = anArray[anIndex];
        aKeyArray = Object.keys(anObj);
        if(aKeyArray.indexOf(aKey)!=-1){
            if(anArray[anIndex][aKey] && 
...