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

JavascriptJson

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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

ary[name] = val;

Solution 4 - Javascript

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

Solution 5 - Javascript

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"}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKim SchroederView Question on Stackoverflow
Solution 1 - JavascriptMattView Answer on Stackoverflow
Solution 2 - JavascriptwheresrhysView Answer on Stackoverflow
Solution 3 - JavascriptJames MontagneView Answer on Stackoverflow
Solution 4 - JavascriptBasilView Answer on Stackoverflow
Solution 5 - JavascriptOlivierView Answer on Stackoverflow