Rename the keys in an object

Viewed 39177
var addObjectResponse = [{
    'SPO2': '222.00000',
    'VitalGroupID': 1152,
    'Temperature': 36.6666666666667,
    'DateTimeTaken': '/Date(1301494335000-0400)/',
    'UserID': 1,
    'Height': 182.88,
    'UserName': 'Admin',
    'BloodPressureDiastolic': 80,
    'Weight': 100909.090909091,
    'TemperatureMethod': 'Oral',
    'Resprate': 111,
    'HeartRate': 111,
    'BloodPressurePosition': 'Standing',
    'VitalSite': 'Popliteal',
    'VitalID': 1135,
    'Laterality': 'Right',
    'HeartRateRegularity': 'Regular',
    'HeadCircumference': '',
    'BloodPressureSystolic': 120,
    'CuffSize': 'XL',
}];

How to rename the keys... like SPO2 into O2... there are such many objects in the array...

10 Answers

Here's one that works over an array of objects and takes a map of old object keys to new object keys.

I mostly copied the very nice code from here and just made it operate over arrays of objects rather than a single one.

Code

const renameKeys = (keysMap, objArr) =>
  (renamedArr = objArr.map((obj) =>
    Object.keys(obj).reduce(
      (acc, key) => ({
        ...acc,
        ...{ [keysMap[key] || key]: obj[key] },
      }),
      {}
    )
  ));

Example

renameKeys({ tWo: 'two', FreE: 'three' }, [
  { one: 1, tWo: 2, three: 3 },
  { one: 100, two: 200, FreE: 300 },
]);
[ { one: 1, two: 2, three: 3 }, { one: 100, two: 200, three: 300 } ]

A little late to the game here but how about something like this:

const newAddObjectResponse = addObjectResponse.map((obj) => {
    const {SPO2: O2, ...rest} = obj
    return {O2, ...rest}
})

If you want to replace your original array then you could do:

let addObjectResponse = [
    {
        SPO2: '222.00000',
        VitalGroupID: 1152,
        Temperature: 36.6666666666667,
        DateTimeTaken: '/Date(1301494335000-0400)/',
        UserID: 1,
        Height: 182.88,
        UserName: 'Admin',
        BloodPressureDiastolic: 80,
        Weight: 100909.090909091,
        TemperatureMethod: 'Oral',
        Resprate: 111,
        HeartRate: 111,
        BloodPressurePosition: 'Standing',
        VitalSite: 'Popliteal',
        VitalID: 1135,
        Laterality: 'Right',
        HeartRateRegularity: 'Regular',
        HeadCircumference: '',
        BloodPressureSystolic: 120,
        CuffSize: 'XL',
    },
]

addObjectResponse = addObjectResponse.map((obj) => {
    const {SPO2: O2, ...rest} = obj
    return {O2, ...rest}
})
Related