将动态键,值对添加到JavaScript数组或哈希表
我正在尝试将键值对添加到现有的javascript关联数组中。关键需要是一个变量。这适用于JSON编码。我知道有很多插件和框架,但我想要一个简单的答案。
I'm trying to add a key value pair to an existing javascript associative array. The key needs to be a variable. This is for JSON encoding. I realize there are many plugins and frameworks for this, but I want a simple answer.
ary.push({name: val});
其中 ary
是一个新数组, name 是一个包含密钥的变量, val
是此条目的值。
where ary
is a new array, name
is a variable containing the key, val
is the value of this entry.
我在 jQuery
循环中执行此操作,该循环遍历表单字段。
I'm doing this in a jQuery
loop that iterates through form fields.
在ES6 ...
在ES6中,您可以使用 destructuring assignment ;
ary.push({[name]: val});
但是,鉴于这是ES6语法,通常的警告适用; 这在某些浏览器中无效(特别是IE和边缘13)......虽然Babel会为你转发这个。
However, given this is ES6 syntax, the usual caveats apply; this will not work in some browsers (noticably, IE and Edge 13)... although Babel will transpile this for you.
您需要定义一个对象并使用方括号表示法来设置属性;
You need to define an object and use square bracket notation to set the property;
var obj = {};
obj[name] = val;
ary.push(obj);
如果您想要更多地阅读它,请参阅本文关于方括号和点符号之间的差异。
If you get the urge to read into it more, see this article on the differences between square bracket and dot notation.