如何在 JavaScript 上的 array.push 上设置 JSON 数组键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8743230/
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
How to set a JSON array key on array.push on JavaScript
提问by pmerino
I'm making some JS code, where I need to set a variable as a key in a JSON array with Javascript array.push()
:
我正在编写一些 JS 代码,我需要在其中使用 Javascript 将变量设置为 JSON 数组中的键array.push()
:
var test = 'dd'+questNumb;
window.voiceTestJSON.push({test:{"title":""}, "content":{"date":""}});
Where questNumb
is another variable. When doing that code, the part where I just write the test
variable it just becomes to the key "test"
, so I have no idea of getting this to wok. How could it be? Thanks!
questNumb
另一个变量在哪里。在执行该代码时,我只是将test
它写入变量的部分变成了 key "test"
,所以我不知道如何让它起作用。怎么会这样?谢谢!
回答by Dennis
If you want variables as keys, you need brackets:
如果要将变量作为键,则需要括号:
var object = {};
object['dd'+questNumb] = {"title":""};
object["content"] = {"date":""}; //Or object.content, but I used brackets for consistency
window.voiceTestJSON.push(object);
回答by jabclab
You'd need to do something like this:
你需要做这样的事情:
var test = "dd" + questNumb,
obj = {content: {date: ""}};
// Add the attribute under the key specified by the 'test' var
obj[test] = {title: ""};
// Put into the Array
window.voiceTestJSON.push(obj);
回答by nnnnnn
(First of all, you don't have a JSON array, you have a JavaScript object. JSON is a string representation of data with a syntax that looks like JavaScript's object literal syntax.)
(首先,您没有 JSON 数组,您有一个 JavaScript 对象。JSON 是数据的字符串表示形式,其语法类似于 JavaScript 的对象字面量语法。)
Unfortunately when you use JavaScript's object literal syntax to create an object you can not use variables to set dynamic property names. You have to create the object first and then add the properties using the obj[propName]
syntax:
不幸的是,当您使用 JavaScript 的对象字面量语法创建对象时,您不能使用变量来设置动态属性名称。您必须先创建对象,然后使用以下obj[propName]
语法添加属性:
var test = "dd" + questNumb,
myObj = { "content" : {"date":""} };
myObj[test] = {"title" : ""};
window.voiceTestJSON.push(myObj);
回答by einPaule
{test:{"title":""}, "content":{"date":""}}
this is a JS object. So you are pushing an object into the voiceTestJSON array.
这是一个 JS 对象。因此,您将一个对象推送到 voiceTestJSON 数组中。
Unlike within JSON, JS Object property names can be written with or without quotes.
与 JSON 不同,JS 对象属性名称可以带引号或不带引号。
What you want to do can be achieved like this:
你想做的事情可以这样实现:
var test = 'dd'+questNumb;
var newObject = {"content":{"date":""}}; //this part does not need a variable property name
newObject[test] = {"title":""};
This way you are setting the property with the name contained in test to {"title":""}.
通过这种方式,您可以将 test 中包含的名称的属性设置为 {"title":""}。