Skip to content
Fix Code Error

JavaScript set object key by variable

March 13, 2021 by Code Error
Posted By: Anonymous

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:

var key = "happyCount";
myArray.push( { key : someValueArray } );

but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?

Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/

Solution

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018:

If you’re able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  
Answered By: Anonymous

Related Articles

  • How to define Typescript Map of key value pair. where key is…
  • Create HTML table using Javascript
  • Typescript Symbol.species typing inference
  • How to vertically align an image inside a div
  • Excel VBA function to print an array to the workbook
  • What is an IndexOutOfRangeException /…
  • Polymer data-binding not updated on array mutation
  • How do I include certain conditions in SQL Count
  • Deleting array elements in JavaScript - delete vs splice
  • Push git commits & tags simultaneously

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do you format an unsigned long long int using printf?

Next Post:

How can I selectively merge or pick changes from another branch in Git?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error