Change key name in JavaScript object

前端 未结 4 607
眼角桃花
眼角桃花 2020-12-10 13:25

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.



        
4条回答
  •  半阙折子戏
    2020-12-10 13:59

    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_', ''); });
    

提交回复
热议问题