Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
Kim Schroeder Avatar asked Feb 22 '12 16:02

Kim Schroeder


People also ask

How can I add a key value pair to a JavaScript array?

To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.

How do you add a key value pair in an object dynamically?

To add dynamic key-value pairs to a JavaScript array or hash table, we can use computed key names. const obj = {}; obj[name] = val; to add a property with the value of name string as the property name. We assign val to as the property's value.

How do you store key-value pairs in an array?

const arr = [ {"name": "Rahul", "score": 89}, {"name": "Vivek", "score": 88}, {"name": "Rakesh", "score": 75}, {"name": "Sourav", "score": 82}, {"name": "Gautam", "score": 91}, {"name": "Sunil", "score": 79}, ];


Video Answer


2 Answers

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.

like image 147
2 revs Avatar answered Sep 25 '22 16:09

2 revs


var ary = [];  function pushToAry(name, val) {    var obj = {};    obj[name] = val;    ary.push(obj); }  pushToAry("myName", "myVal"); 

Having just fully read your question though, all you need is the following

$(your collection of form els).serializeArray(); 

Good old jQuery

like image 30
wheresrhys Avatar answered Sep 22 '22 16:09

wheresrhys