[removed] Object Rename Key

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

    Yet another way with the most powerful REDUCE method.

    data = {key1: "value1", key2: "value2", key3: "value3"}; 
    
    keyMap = {key1: "firstkey", key2: "secondkey", key3: "thirdkey"};
    
    mappedData = Object.keys(keyMap).reduce((obj,k) => Object.assign(obj, { [keyMap[k]]: data[k] }),{});
    
    console.log(mappedData);

提交回复
热议问题