Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename the keys in an object

Tags:

javascript

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...

like image 671
John Cooper Avatar asked Aug 04 '11 13:08

John Cooper


2 Answers

maybe something like this?

var i, len = addObjectResponse.length;
for (i = 0; i < len; i++) {
    addObjectResponse[i]['O2'] = addObjectResponse[i]['SPO2'];
    delete addObjectResponse[i]['SPO2'];
}

or

addObjectResponse = addObjectResponse.map(function (obj) {
    obj['O2'] = obj['SP02'];
    delete obj['S02'];
    return obj;
});

or

for (let obj of addObjectResponse) {
    obj['O2'] = obj['SP02'];
    delete obj['S02'];
}

or

function renameProperty(obj, fromKey, toKey) {
    obj[toKey] = obj[fromKey];
    delete obj[fromKey];
}

addObjectResponse.forEach(obj => renameProperty(obj, 'SP02', 'O2'));
like image 76
Ilia Choly Avatar answered Sep 23 '22 05:09

Ilia Choly


You cannot directly rename the properties. However, you can set new properties and unset the old ones, indirectly "renaming" them:

function rename(obj, oldName, newName) {
    if(!obj.hasOwnProperty(oldName)) {
        return false;
    }

    obj[newName] = obj[oldName];
    delete obj[oldName];
    return true;
}
like image 36
Jon Avatar answered Sep 20 '22 05:09

Jon