82

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.

Saurabh
  • 71,488
  • 40
  • 181
  • 244
Kim Schroeder
  • 921
  • 1
  • 6
  • 5
  • possible duplicate of [Passing in dynamic key:value pairs to an object literal?](http://stackoverflow.com/questions/4119324/passing-in-dynamic-keyvalue-pairs-to-an-object-literal) --- please use the search before you ask a question. – Felix Kling Feb 22 '12 at 16:21
  • 3
    Do you want `ary` = [ key: value, key: value, ...]` or `ary = [{key: value}, {key: value}, ... ]` ? – wheresrhys Feb 22 '12 at 16:22

5 Answers5

215

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.

Matt
  • 74,352
  • 26
  • 153
  • 180
  • 1
    This is the answer. Thank You! i was enting up with ary[] company "kim corp" email "eml1" when i declares the array as Array – Kim Schroeder Feb 22 '12 at 17:30
  • 17
    If this is your answer, you should mark it as such, so Matt get's credit, and people can easily see which answer worked for you. – Atomox Aug 09 '12 at 20:28
  • This helped me out. I had multiple name/value pairs in an array object - e.g. in PHP: `$test = array(); $test[] = array ("description" => "first", "identifier" => "1");`. To add to that in JavaScript it is just `var obj = {}; obj["description"] = "second"; obj["identifier"] = 2; ary.push(obj);` where ary is the JavaScript variable that was assigned the PHP array. – Gravitoid Oct 15 '13 at 13:44
  • Especially the first. ES6 syntax does exactly as I expected. I get a plain key-value pair with the "dynamic" keyname. So it doesn't work in IE... what else is new. – Non Plus Ultra Mar 15 '17 at 10:54
39
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

wheresrhys
  • 22,558
  • 19
  • 94
  • 162
27

An "associative array" is really just an object. You don't use push, you just assign properties to the object:

ary[name] = val;
James Montagne
  • 77,516
  • 14
  • 110
  • 130
6

The following code will help you

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

See below example

let allData = [{name: "Cat", type: "Animal"}]
let finalData: any = [];
for (let i = 0; i < allData.length; i++)
{
  let obj = allData[i];
  for (let KEY in obj)
  {
    //Pushing data to other array as object
    this.finalData.push({ [KEY] : obj[KEY] });
  }
}
Basil
  • 1,664
  • 13
  • 25
2
const tStyles = [];
for (const i of iStyles) {
  const temp = {};
  temp[`${style}`] = `../dist/css/uikit.${wFile}.${style}.css`;
  tStyles.push(temp);
}

json : {"black-beige":"../dist/css/uikit.or.black-beige.css"}

Olivier
  • 519
  • 5
  • 8