[removed] Object Rename Key

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

    A variation using object destructuring and spread operator:

        const old_obj = {
            k1: `111`,
            k2: `222`,
            k3: `333`
        };
    
    
    // destructuring, with renaming. The variable 'rest' will hold those values not assigned to kA, kB, or kC.
        const {
            k1: kA, 
            k2: kB, 
            k3: kC,
            ...rest
        } = old_obj;
    
    
    // now create a new object, with the renamed properties kA, kB, kC; 
    // spread the remaining original properties in the 'rest' variable
    const newObj = {kA, kB, kC, ...rest};
    

提交回复
热议问题