Javascript 动态命名 JSON 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2318532/
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-22 23:45:06  来源:igfitidea点击:

Dynamically name a JSON property

javascriptjson

提问by Helton Valentini

I've been trying to create a dynamically named JSON property but I keep hitting on errors. Honestly I don't know if this is possible to achieve with Javascript. Anyway here is my problem.

我一直在尝试创建一个动态命名的 JSON 属性,但我一直遇到错误。老实说,我不知道这是否可以用 Javascript 实现。无论如何,这是我的问题。

Let's suppose I'm creating a JSON object like the following code:

假设我正在创建一个 JSON 对象,如下面的代码:

var DTO = { 'NewObject' : GetFormData() };  
var DTO = { 'UpdateObject' : GetFormData() };  
var DTO = { 'DelObject' : GetFormData() };  

Now what I've been trying to do is to dynamically name the JSON property because with something like 'New' + ClassName(ClassNamebeing a var with a string value) but it gives me a syntax error. Is there a way to do this to become something like:

现在我一直在尝试做的是动态命名 JSON 属性,因为类似于'New' + ClassNameClassName是一个带有字符串值的 var),但它给了我一个语法错误。有没有办法做到这一点,成为这样的:

var DTO = { 'New' + ClassName : GetFormData() };  
var DTO = { 'Update' + ClassName : GetFormData() };  
var DTO = { 'Delete' + ClassName : GetFormData() };  

I really appreciate your help. Thanks.

我真的很感谢你的帮助。谢谢。

回答by instanceof me

Would this suit your needs ?

这是否适合您的需求?

var DTO = {}; DTO['New' + ClassName] = GetFormData();

回答by Quentin

This is just "an object". JSON is a serialization to a string, not an object type.

这只是“一个对象”。JSON 是字符串的序列化,而不是对象类型。

If you want to use a variable as a property name, then you must create an object first, then assign the data using square bracket notation.

如果要将变量用作属性名称,则必须先创建一个对象,然后使用方括号表示法分配数据。

var foo = {};
var bar = 'baz';
foo[bar] = '123';
alert(foo.baz);

回答by Dylan Hogg

With ECMAScript 6, you can use computed property names in object property definitions.

使用 ECMAScript 6,您可以在对象属性定义中使用计算属性名称。

For example, you can simply write:

例如,您可以简单地编写:

var DTO = { ['New' + ClassName] : GetFormData() };

More information: http://es6-features.org/#ComputedPropertyNames

更多信息:http: //es6-features.org/#ComputedPropertyNames

回答by Ignacio Vazquez-Abrams

var DTO = Object();
DTO['New' + ClassName] = GetFormData();