I am checking the attributes in a JavaScript object, replacing some of the keys by deleting the prefix \"element\" and saving the new values in another object.
Try this:
var keys = Object.keys(json);
for (var j=0; j < keys.length; j++) {
var key = keys[j]; // key
var value = json[key]; // data
delete json[key]; // deleting data with old key
key = key.replace("element_", ""); // renaming key
json[key] = value; // setting data with new key
}
or extend prototype of Object
Object.prototype.renameKey = function (oldName, newName) {
if (!newName) return this;
if (oldName === newName) return this;
if (this.hasOwnProperty(oldName)) {
this[newName] = this[oldName];
delete this[oldName];
}
return this;
};
var keys = Object.keys(json);
keys.forEach(function(key) { json.renameKey(key, key.replace('element_', ''); });