Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
806 views
in Technique[技术] by (71.8m points)

json - Add dynamic key, value pairs to JavaScript array or hash table

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

where ary is a new array, name is a variable containing the key, val is the value of this entry.

I'm doing this in a jQuery loop that iterates through form fields.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In ES6...

In ES6, you can use a destructuring assignment;

ary.push({[name]: val});

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.


Without ES6 (legacy browser support)...

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...