[removed] Object Rename Key

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

    This is a small modification that I made to the function of pomber; To be able to take an Array of Objects instead of an object alone and also you can activate index. also the "Keys" can be assigned by an array

    function renameKeys(arrayObject, newKeys, index = false) {
        let newArray = [];
        arrayObject.forEach((obj,item)=>{
            const keyValues = Object.keys(obj).map((key,i) => {
                return {[newKeys[i] || key]:obj[key]}
            });
            let id = (index) ? {'ID':item} : {}; 
            newArray.push(Object.assign(id, ...keyValues));
        });
        return newArray;
    }
    

    test

    const obj = [{ a: "1", b: "2" }, { a: "5", b: "4" } ,{ a: "3", b: "0" }];
    const newKeys = ["A","C"];
    const renamedObj = renameKeys(obj, newKeys);
    console.log(renamedObj);
    
    0 讨论(0)
  • 2020-11-22 01:17
    • You can use a utility to handle this.
    npm i paix
    
    import { paix } from 'paix';
    
    const source_object = { FirstName: "Jhon", LastName: "Doe", Ignored: true };
    const replacement = { FirstName: 'first_name', LastName: 'last_name' };
    const modified_object = paix(source_object, replacement);
    
    console.log(modified_object);
    // { Ignored: true, first_name: 'Jhon', last_name: 'Doe' };
    
    
    0 讨论(0)
  • 2020-11-22 01:19

    Personally, the most effective way to rename keys in object without implementing extra heavy plugins and wheels:

    var str = JSON.stringify(object);
    str = str.replace(/oldKey/g, 'newKey');
    str = str.replace(/oldKey2/g, 'newKey2');
    
    object = JSON.parse(str);
    

    You can also wrap it in try-catch if your object has invalid structure. Works perfectly :)

    0 讨论(0)
  • 2020-11-22 01:19

    Your way is optimized, in my opinion. But you will end up with reordered keys. Newly created key will be appended at the end. I know you should never rely on key order, but if you need to preserve it, you will need to go through all keys and construct new object one by one, replacing the key in question during that process.

    Like this:

    var new_o={};
    for (var i in o)
    {
       if (i==old_key) new_o[new_key]=o[old_key];
       else new_o[i]=o[i];
    }
    o=new_o;
    
    0 讨论(0)
  • 2020-11-22 01:19

    Trying using lodash transform.

    var _ = require('lodash');
    
    obj = {
      "name": "abc",
      "add": "xyz"
    };
    
    var newObject = _.transform(obj, function(result, val, key) {
    
      if (key === "add") {
        result["address"] = val
      } else {
        result[key] = val
      }
    });
    console.log(obj);
    console.log(newObject);
    
    0 讨论(0)
  • 2020-11-22 01:20

    Here is an example to create a new object with renamed keys.

    let x = { id: "checkout", name: "git checkout", description: "checkout repository" };
    
    let renamed = Object.entries(x).reduce((u, [n, v]) => {
      u[`__${n}`] = v;
      return u;
    }, {});
    
    0 讨论(0)
提交回复
热议问题