[removed] Object Rename Key

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

    You can try lodash _.mapKeys.

    var user = {
      name: "Andrew",
      id: 25,
      reported: false
    };
    
    var renamed = _.mapKeys(user, function(value, key) {
      return key + "_" + user.id;
    });
    
    console.log(renamed);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

    0 讨论(0)
  • 2020-11-22 00:57

    just try it in your favorite editor <3

    const obj = {1: 'a', 2: 'b', 3: 'c'}
    
    const OLD_KEY = 1
    const NEW_KEY = 10
    
    const { [OLD_KEY]: replaceByKey, ...rest } = obj
    const new_obj = {
      ...rest,
      [NEW_KEY]: replaceByKey
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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};
    
    0 讨论(0)
  • 2020-11-22 01:01
    const data = res
    const lista = []
    let newElement: any
    
    if (data && data.length > 0) {
    
      data.forEach(element => {
          newElement = element
    
          Object.entries(newElement).map(([key, value]) =>
            Object.assign(newElement, {
              [key.toLowerCase()]: value
            }, delete newElement[key], delete newElement['_id'])
          )
        lista.push(newElement)
      })
    }
    return lista
    
    0 讨论(0)
  • 2020-11-22 01:02

    I would like just using the ES6(ES2015) way!

    we need keeping up with the times!

    const old_obj = {
        k1: `111`,
        k2: `222`,
        k3: `333`
    };
    console.log(`old_obj =\n`, old_obj);
    // {k1: "111", k2: "222", k3: "333"}
    
    
    /**
     * @author xgqfrms
     * @description ES6 ...spread & Destructuring Assignment
     */
    
    const {
        k1: kA, 
        k2: kB, 
        k3: kC,
    } = {...old_obj}
    
    console.log(`kA = ${kA},`, `kB = ${kB},`, `kC = ${kC}\n`);
    // kA = 111, kB = 222, kC = 333
    
    const new_obj = Object.assign(
        {},
        {
            kA,
            kB,
            kC
        }
    );
    
    console.log(`new_obj =\n`, new_obj);
    // {kA: "111", kB: "222", kC: "333"}

    0 讨论(0)
提交回复
热议问题