change property name

后端 未结 4 1338
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 07:44

I have a JavaScript object as follows:

var a = { Prop1: \'test\', Prop2: \'test2\' }

How would I change the \"property name\" of Prop1 to P

相关标签:
4条回答
  • 2020-11-28 08:21

    Using the proposed property rest notation, write

    const {Prop1, ...otherProps} = a;
    
    const newObj = {Prop3: Prop1, ...otherProps};
    

    This is supported by Babel's object rest spread transform.

    0 讨论(0)
  • 2020-11-28 08:36

    That isn't directly possible.

    You can just write

    a.Prop3 = a.Prop1;
    delete a.Prop1;
    
    0 讨论(0)
  • 2020-11-28 08:37

    Workaround

    Convert your Object to a String using JSON.stringify, then replace any occurrences of Prop1 with Prop3 using str.replace("Prop1", "Prop3"). Finally, convert your string back to an Object using JSON.parse(str).

    Note: str.replace("Prop1", "Prop3") will only replace the first occurrence of "Prop1" in the JSON string. To replace multiple, use this regex syntax instead: str.replace(/Prop1/g, "Prop3") Refrence Here

    Demo

    http://jsfiddle.net/9hj8k0ju/

    Example

    var a  = { Prop1: 'test', Prop2: 'test2' }
    str = JSON.stringify(a);
    str = str.replace("Prop1","Prop3");
    var converted  = JSON.parse(str);
    
    0 讨论(0)
  • 2020-11-28 08:42

    Adding to the object rest spread solution

    const { Prop1: Prop3, ...otherProps } = a;
    const newObj = { Prop3, ...otherProps };
    
    0 讨论(0)
提交回复
热议问题