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.

2
  • possible duplicate of Passing in dynamic key:value pairs to an object literal? --- please use the search before you ask a question. Commented Feb 22, 2012 at 16:21
  • 3
    Do you want ary = [ key: value, key: value, ...]` or ary = [{key: value}, {key: value}, ... ] ? Commented Feb 22, 2012 at 16:22

5 Answers 5

217

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is the answer. Thank You! i was enting up with ary[] company "kim corp" email "eml1" when i declares the array as Array
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.
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.
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.
41
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

Comments

27

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

ary[name] = val;

2 Comments

It should do that i agree. I'll post all the code and hope you can see where the mistake is
this is the best answer. very simple, and all that's needed if you already have a hash defined.
7

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.