javascript 即时创建 json 键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11036644/
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
Creating json keys on the fly
提问by Eruant
I would like to create a json
object to send as a post array, but I need to create the key on the fly
我想创建一个json
对象作为 post 数组发送,但我需要即时创建密钥
var id = $('#myInput').val();
var post = {
'product[123]': 'myValue', // this works fine - but isn't dynamic
'product['+id+']': 'myValue' // this does not work
}
Sending it in as a string works fine, but I get an issue when I want to make it more dynamic. Am I missing something really simple here, or am I trying to do something Javascript isn't supposed to do?
将它作为字符串发送工作正常,但是当我想让它更动态时出现问题。我在这里遗漏了一些非常简单的东西,还是我试图做一些 Javascript 不应该做的事情?
回答by T.J. Crowder
(Note that this has nothing to do with JSON. You're not using JSON there, you're using an object initializer. JSONis a textual (not code) format, which is a subsetof JavaScript's object initializer syntax.)
(请注意,这已经无关JSON。您没有使用JSON那里,你正在使用的对象初始化。JSON是文本(不是代码)格式,这是一个子集,JavaScript的对象初始化语法的。)
Do it outside the object initializer, using []
notation:
使用[]
符号在对象初始值设定项之外执行此操作:
var id = $('#myInput').val();
var post = {};
post[product[id]] = 'myValue';
That will take the value (at runtime) of product[id]
and use that as the key for the property. If you wanted the key to literallybe product[123]
when id
is 123
, you'd use this instead:
这将取值(在运行时)product[id]
并将其用作属性的键。如果您希望密钥字面上是product[123]
when id
is 123
,则可以改用它:
post['product[' + id + ']'] = 'myValue';
A more generic discussion:
更一般的讨论:
var a = "foo";
var obj = {};
obj[a] = "bar";
console.log(obj.foo); // "bar"
JavaScript allows you to specify property keys in two ways: Using dotted notation and a literal (obj.foo
), or using bracketed notation and a string (obj["foo"]
). In the latter case, the string doesn't have to be a string literal, it can be the result of any expression.
JavaScript 允许您以两种方式指定属性键:使用点符号和文字 ( obj.foo
),或使用方括号符号和字符串 ( obj["foo"]
)。在后一种情况下,字符串不必是字符串文字,它可以是任何表达式的结果。
回答by Mottie
Try
尝试
post['product[' + id + ']'] = 'myValue';
回答by Jerry
Why do you use '[ ]' in ids of the object? Avoid to do this.
In your sample, you can do this by the following code:
为什么在对象的 id 中使用“[]”?避免这样做。
在您的示例中,您可以通过以下代码执行此操作:
var id = $('#myInput').val();
var post = {
'123': 'myValue',
id: 'myValue'
}
Or, if you realy realy want to use an arrry (actually, all objects ARE array in JavaScript).
You can write this:
或者,如果您真的很想使用数组(实际上,JavaScript 中的所有对象都是数组)。你可以这样写:
var product=[];
product['123']='something';
product[id]='another';