[removed] Object Rename Key

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

    In case someone needs to rename a list of properties:

    function renameKeys(obj, newKeys) {
      const keyValues = Object.keys(obj).map(key => {
        const newKey = newKeys[key] || key;
        return { [newKey]: obj[key] };
      });
      return Object.assign({}, ...keyValues);
    }
    

    Usage:

    const obj = { a: "1", b: "2" };
    const newKeys = { a: "A", c: "C" };
    const renamedObj = renameKeys(obj, newKeys);
    console.log(renamedObj);
    // {A:"1", b:"2"}
    

提交回复
热议问题