Javascript 更改属性名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8483425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:10:36  来源:igfitidea点击:

change property name

javascript

提问by firebird

I have a JavaScript object as follows:

我有一个 JavaScript 对象,如下所示:

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

How would I change the "property name" of Prop1 to Prop3?

如何将 Prop1 的“属性名称”更改为 Prop3?

I tried

我试过

for (var p in r) p.propertyName = 'Prop3';

but that did not work.

但这没有用。

回答by SLaks

That isn't directly possible.

这不是直接可能的。

You can just write

你可以写

a.Prop3 = a.Prop1;
delete a.Prop1;

回答by firebird

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.

Babel 的object rest spread transform支持这一点。

回答by kendotwill

Adding to the object rest spread solution

添加到对象休息传播解决方案

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

回答by Rafael Ribeiro

Workaround

解决方法

Convert your Objectto a Stringusing JSON.stringify, then replace any occurrences of Prop1with Prop3using str.replace("Prop1", "Prop3"). Finally, convert your string back to an Objectusing JSON.parse(str).

将您ObjectString使用JSON.stringify,然后更换任何出现Prop1Prop3使用str.replace("Prop1", "Prop3")。最后,将您的字符串转换回Objectusing 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

注意:str.replace("Prop1", "Prop3")只会替换 JSON 字符串中第一次出现的“Prop1”。要替换多个,请改用此正则表达式语法: str.replace(/Prop1/g, "Prop3")Refrence Here

Demo

演示

http://jsfiddle.net/9hj8k0ju/

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);