[removed] Object Rename Key

前端 未结 24 1385
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 00:18

Is there a clever (i.e. optimized) way to rename a key in a javascript object?

A non-optimized way would be:

o[ new_key ] = o[ old_key ];
delete o[ o         


        
24条回答
  •  心在旅途
    2020-11-22 01:08

    Some of the solutions listed on this page have some side-effects:

    1. affect the position of the key in the object, adding it to the bottom (if this matters to you)
    2. would not work in IE9+ (again, if this matters to you)

    Here is a solution which keeps the position of the key in the same place and is compatible in IE9+, but has to create a new object and may not be the fastest solution:

    function renameObjectKey(oldObj, oldName, newName) {
        const newObj = {};
    
        Object.keys(oldObj).forEach(key => {
            const value = oldObj[key];
    
            if (key === oldName) {
                newObj[newName] = value;
            } else {
                newObj[key] = value;
            }
        });
    
        return newObj;
    }
    

    Please note: IE9 may not support forEach in strict mode

提交回复
热议问题