[removed] Object Rename Key

前端 未结 24 1355
爱一瞬间的悲伤
爱一瞬间的悲伤 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 00:58

    Most of the answers here fail to maintain JS Object key-value pairs order. If you have a form of object key-value pairs on the screen that you want to modify, for example, it is important to preserve the order of object entries.

    The ES6 way of looping through the JS object and replacing key-value pair with the new pair with a modified key name would be something like:

    let newWordsObject = {};
    
    Object.keys(oldObject).forEach(key => {
      if (key === oldKey) {
        let newPair = { [newKey]: oldObject[oldKey] };
        newWordsObject = { ...newWordsObject, ...newPair }
      } else {
        newWordsObject = { ...newWordsObject, [key]: oldObject[key] }
      }
    });
    

    The solution preserves the order of entries by adding the new entry in the place of the old one.

提交回复
热议问题