Home > other >  Rename (add suffix to) every key except 2 in every object in array of objects javascript
Rename (add suffix to) every key except 2 in every object in array of objects javascript

Time:11-20

We have the following javascript array:

[
  { team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 },
  { team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 },
  { team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 }
]

and we are looking to add the suffix Agst to every key other than the team key, such that our output is:

[
  { team: 1, stat1Agst: 17, stat2Agst: 25, var1Agst: 'okay', var3Agst: 'nah', hereAgst: 24 },
  { team: 1, stat1Agst: 17, stat2Agst: 25, var1Agst: 'okay', var3Agst: 'nah', hereAgst: 24 },
  { team: 1, stat1Agst: 17, stat2Agst: 25, var1Agst: 'okay', var3Agst: 'nah', hereAgst: 24 }
]

Each object in our actual array of objects has >100 keys, and for this reason we are looking for a solution that specifically changes all key names other than team, rather than changing all keys with names ['stat1', 'stat2', 'var1', 'var3', 'here'] if possible.

CodePudding user response:

You can easily achieve the result using map and Object.entries as:

const arr = [
  { team: 1, stat1: 17, stat2: 25, var1: "okay", var3: "nah", here: 24 },
  { team: 1, stat1: 17, stat2: 25, var1: "okay", var3: "nah", here: 24 },
  { team: 1, stat1: 17, stat2: 25, var1: "okay", var3: "nah", here: 24 },
];

const result = arr.map((o) =>
  Object.fromEntries(
    Object.keys(o).map((key) =>
      key === "team" ? [key, o[key]] : [`${key}Agst`, o[key]]
    )
  )
);

console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This seems to be working okay for me.

arr = [
  { team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 },
  { team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 },
  { team: 1, stat1: 17, stat2: 25, var1: 'okay', var3: 'nah', here: 24 }
]

arr.forEach((row, index, theArray) => {
    let rowKeys = Object.keys(row).filter(key => key !== 'team');
    rowKeys.forEach(key => {
        theArray[index][`${key}Agst`] = theArray[index][key];
        delete theArray[index][key];
    });
});

console.log(arr);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related