How do I create a dynamic key to be added to a JavaScript object variable
Square brackets:
jsObj['key' + i] = 'example' + 1;
In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length
property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0"
, "5"
, "207"
, and so on, are all treated specially in that their existence determines the value of length
. And, on top of that, the value of length
can be set to remove such properties. Setting the length
of an array to 0
effectively removes all properties whose names look like whole numbers.
OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ]
operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.
Thus, the way the [ ]
operator works in a for
loop iterating through an array:
for (var i = 0; i < myArray.length; ++i) {
var value = myArray[i]; // property access
// ...
}
is really no different from the way [ ]
works when accessing a property whose name is some computed string:
var value = jsObj["key" + i];
The [ ]
operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.
When setting property values using [ ]
, the story is the same except for the special behavior around maintaining the length
property. If you set a property with a numeric key on an array instance:
myArray[200] = 5;
then (assuming that "200" is the biggest numeric property name) the length
property will be updated to 201
as a side-effect of the property assignment. If the same thing is done to a plain object, however:
myObj[200] = 5;
there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5
in otherwise the exact same way.
One might think that because that length
behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length
but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:
var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;
var objJSON = JSON.stringify(obj);
the value of "objJSON" will be a string containing just ["hello world"]
; the "something" property will be lost.
ES2015:
If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:
var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
};
console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }
Creating object with dynamic keys
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
How to add dynamic key with value in existing Javascript object?
You can do this with Object.assign() and using Computed Property names (example {[key]: value}
):
let existingObject = {
1: {'prop1': 'prop1 value', 'prop2': 'prop2 value'},
2: {'prop1': 'prop1 value', 'prop2': 'prop2 value'},
3: {'prop1': 'prop1 value', 'prop2': 'prop2 value'}
}
const key = 4;
const value = {'prop1': 'prop1 value', 'prop2': 'prop2 value'}
Object.assign(existingObject, {[key]: value});
console.log(existingObject);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
How to save dynamic key reference when creating an object in javascript?
You could use an immediately invoked (arrow) function, together with some other ES6 syntax:
let obj = (id => ({ [id]: {id} }))(uuid());
As a side note: better use camelCase for variable names, and reserve the initial-capital notation only for constructors/classes.
Is it possible to add dynamically named properties to JavaScript object?
Yes.
var data = { 'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3};
data["PropertyD"] = 4;
// dialog box with 4 in italert(data.PropertyD);alert(data["PropertyD"]);
JavaScript set object key by variable
You need to make the object first, then use []
to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
JavaScript, update object with dynamic keys
Use Computed property names
This is reminiscent of the bracket notation of the property accessor
syntax
let obj = { "id": "", "id_configuration": "", "comment": "", "mw_assigned": "",};
const key = 'mw_assigned'const value = '23'
const new_obj = { ...obj, [key]: value }
console.log(new_obj)
Set dynamic key and values inside for loop
To set a dynamic string as a property of an object, you can use square bracket notation (obj[propVariable]
). So, just store an empty object into a variable (var item = {}
), and then you can set its property through item[propVariable]
.
var list = [];var names = ["Bob","Tom","Larry"];var ages = ["10", "20", "30"];for(var i=0; i<names.length; i++){ var item = {}; item[ages[i]] = names[i]; list.push(item);}console.log(list);
Related Topics
How to Deal with Big Numbers in JavaScript
Why Variable Hoisting After Return Works on Some Browsers, and Some Not
How to Find Index of All Occurrences of Element in Array
Javascript: Inline Script with Src Attribute
How to Replace While Loops with a Functional Programming Alternative Without Tail Call Optimization
Get the Closest Number Out of an Array
How to JSON.Stringify an Es6 Map
How to Populate a Cascading Dropdown with Jquery
Browser JavaScript Stack Size Limit
Getting Around X-Frame-Options Deny in a Chrome Extension
What Is Minimum Millisecond Value of Settimeout
Jqgrid Incorrect Select Drop Down Option Values in Edit Box
How to Customize Object Equality for JavaScript Set
How to Turn This Callback into a Promise Using Async/Await
Hot and Cold Observables: Are There 'Hot' and 'Cold' Operators
How to Escape a JSON String Containing Newline Characters Using JavaScript