Is it possible to add dynamically named properties to JavaScript object?Use a concatenated (dynamic) string as JavaScript object key?Passing in dynamic key:value pairs to an object literal?Create an object with dynamic property namesHow to add attribute in JSON in Javascript?How to create an object with dynamic property namesObject key name with a variableHow do I dynamically denote my object property names?How can I push an array into an objectIs it possible to add a new property to existing JSON data?Use 'Number' as Object.Keys and Increment ThemLength of a JavaScript objectDetecting an undefined object propertyWhat is the most efficient way to deep clone an object in JavaScript?How can I merge properties of two JavaScript objects dynamically?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How do I test for an empty JavaScript object?How do I correctly clone a JavaScript object?Checking if a key exists in a JavaScript object?Sort array of objects by string property value
Generator for parity?
English - Acceptable use of parentheses in an author's name
Are there any differences in causality between linear and logistic regression?
Was this a rapid SCHEDULED disassembly? How was it done?
Infeasibility in mathematical optimization models
Does a code snippet compile? Or does it get compiled?
Ex-contractor published company source code and secrets online
Why did the RAAF procure the F/A-18 despite being purpose-built for carriers?
TColorBox and Tikz, arrows are not on the diagram
Can a fight scene, component-wise, be too complex and complicated?
What does Apple mean by "This may decrease battery life"?
If a Contingency spell has been cast on a creature, does the Simulacrum spell transfer the contingent spell to its duplicate?
Are any jet engines used in combat aircraft water cooled?
How do I explain to a team that the project they will work on for six months will certainly be cancelled?
What is my malfunctioning AI harvesting from humans?
Why level 0 espers are considered espers if they have no powers at all?
How can you evade tax by getting employment income just in equity, then using this equity as collateral to take out loan?
What are the uses and limitations of Persuasion, Insight, and Deception against other PCs?
Was the 2019 Lion King film made through motion capture?
Table content alignment to centre using tabular
What does "sardine box" mean?
How to vertically align the three columns of my table top, top, middle
Why aren’t emergency services using callsigns?
Does this Foo machine halt?
Is it possible to add dynamically named properties to JavaScript object?
Use a concatenated (dynamic) string as JavaScript object key?Passing in dynamic key:value pairs to an object literal?Create an object with dynamic property namesHow to add attribute in JSON in Javascript?How to create an object with dynamic property namesObject key name with a variableHow do I dynamically denote my object property names?How can I push an array into an objectIs it possible to add a new property to existing JSON data?Use 'Number' as Object.Keys and Increment ThemLength of a JavaScript objectDetecting an undefined object propertyWhat is the most efficient way to deep clone an object in JavaScript?How can I merge properties of two JavaScript objects dynamically?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?How do I test for an empty JavaScript object?How do I correctly clone a JavaScript object?Checking if a key exists in a JavaScript object?Sort array of objects by string property value
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
In JavaScript, I've created an object like so:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
Is it possible to add further properties to this object after it's initial creation if the properties name is not determined until run time? i.e.
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
javascript
add a comment |
In JavaScript, I've created an object like so:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
Is it possible to add further properties to this object after it's initial creation if the properties name is not determined until run time? i.e.
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
javascript
add a comment |
In JavaScript, I've created an object like so:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
Is it possible to add further properties to this object after it's initial creation if the properties name is not determined until run time? i.e.
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
javascript
In JavaScript, I've created an object like so:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
Is it possible to add further properties to this object after it's initial creation if the properties name is not determined until run time? i.e.
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
javascript
javascript
edited Dec 28 '15 at 9:16
Toby Allen
8,8978 gold badges64 silver badges118 bronze badges
8,8978 gold badges64 silver badges118 bronze badges
asked Jul 26 '09 at 9:24
Lee DLee D
5,0937 gold badges27 silver badges33 bronze badges
5,0937 gold badges27 silver badges33 bronze badges
add a comment |
add a comment |
17 Answers
17
active
oldest
votes
Yes.
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
68
data.PropertyD = 4 would also work.
– thedz
Jul 26 '09 at 9:41
130
@thedz: data.PropertyD needs to know the property name, which isn't dynamic enough.
– Georg Schölly
Jul 26 '09 at 9:54
6
+1 because this helped me. But I don't understand why an object properties is handled like an array.
– Ron van der Heijden
Mar 5 '13 at 11:56
9
@Bondye: That's part of the strange design of javascript. In this caseobject["property"]
is not exactly the same asarray[4]
, the former wasn't created as a true array.
– Georg Schölly
Mar 5 '13 at 12:15
16
@Qantas: Let's say it doesn't answer it directly. But going fromdata["PropertyD"]
todata[function_to_get_property_name()]
seems trivial.
– Georg Schölly
Feb 24 '14 at 10:17
|
show 14 more comments
ES6 for the win!
const b = 'b';
const c = 'c';
const data =
a: true,
[b]: true, // dynamic property
[`interpolated-$c`]: true, // dynamic property + interpolation
[`$b-$c`]: true
If you log data
you get this:
a: true,
b: true,
interpolated-c: true,
b-c: true
This makes use of the new Computed Property syntax and Template Literals.
1
This is what I needed in the case where I wanted my code to be completely functional (as in, no imperative statements sayingobj[propname]
). Instead, I was able to use this with object spread syntax.
– intcreator
Feb 13 '18 at 5:41
1
It is not immediately obvious what this code snippet is doing to someone who hasn't seen or comprehended the new syntax. I would suggest an edit to display the output / expected properies with the 'a' const.
– Alexander Pritchard
Mar 20 '18 at 16:47
Personally, I think the ES5 way is a lot cleaner and easier to understand:var a = ; a["dynamic-" + prop] = true;
– Jack Giffin
Apr 3 '18 at 16:39
1
@JackGiffin in some cases yes, but when working with immutable structures, this syntax can be very handy, since the approach you showed is mutatinga
. (Specially when using packages like redux)
– Mauricio Soares
Aug 10 '18 at 9:35
3
This is just great ...state, [prop]: val
– Xipo
Aug 23 '18 at 14:33
|
show 1 more comment
Yes it is possible. Assuming:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propertyName = "someProperty";
var propertyValue = "someValue";
Either:
data[propertyName] = propertyValue;
or
eval("data." + propertyName + " = '" + propertyValue + "'");
The first method is preferred. eval() has the obvious security concerns if you're using values supplied by the user so don't use it if you can avoid it but it's worth knowing it exists and what it can do.
You can reference this with:
alert(data.someProperty);
or
data(data["someProperty"]);
or
alert(data[propertyName]);
38
Using eval is really dangerous.
– Georg Schölly
Jul 26 '09 at 9:29
10
Not to mention slow.
– Eamon Nerbonne
Jul 26 '09 at 11:46
3
JQuery Extend can also be used api.jquery.com/jQuery.extend
– learnerplates
Oct 18 '12 at 11:23
@GeorgSchölly True.
– Obinna Nwakwue
Aug 28 '16 at 14:47
1
Note (in case someone runs into the same issue as I did): For normal objects this works fine. But I had to add some property to a jQuery UI object to keep track of a list of items. In that case, the property was lost if added this way because jQuery always creates a copy. Here you need to use jQuery.extend().
– Matt
Jul 7 '17 at 11:03
|
show 1 more comment
I know that the question is answered perfectly, but I also found another way to add new properties and wanted to share it with you:
You can use the function Object.defineProperty()
Found on Mozilla Developer Network
Example:
var o = ; // Creates a new object
// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", value : 37,
writable : true,
enumerable : true,
configurable : true);
// 'a' property exists in the o object and its value is 37
// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", get : function() return bValue; ,
set : function(newValue) bValue = newValue; ,
enumerable : true,
configurable : true);
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined
// You cannot try to mix both :
Object.defineProperty(o, "conflict", value: 0x9f91102,
get: function() return 0xdeadbeef; );
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
4
Pros and cons of this method?
– Trevor
Jan 14 '14 at 21:06
5
@Trevor: Total configurability and ability to add getters and setters; also, ability to add multiple properties at once withdefineProperties
(plural).
– rvighne
Aug 10 '14 at 1:08
@ThieliciousObject.defineProperty
isn’t meant to be the easy convenience tool, but the one with the fine-grained control. If you don’t need that additional control, it’s not the right tool to choose.
– kleinfreund
Sep 6 '17 at 9:00
Object.defineProperty(obj, prop, valueDescriptor)
is a lot slower and harder for V8 to optimize than simply doingobj[prop] = value
;
– Jack Giffin
Apr 3 '18 at 16:37
add a comment |
Here, using your notation:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
data[propName] = 'Some New Property value'
add a comment |
in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:
var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex =
[ personId ]: person
// ^ computed property name
;
personIndex[ personId ]; // "John Doe"
reference: Understanding ECMAScript 6 - Nickolas Zakas
add a comment |
You can add as many more properties as you like simply by using the dot notation:
var data =
var1:'somevalue'
data.newAttribute = 'newvalue'
or:
data[newattribute] = somevalue
for dynamic keys.
3
if the properties name is not determined until run time" - so that won't work unless you use eval, which isn't a good option
– Marc Gravell♦
Jul 26 '09 at 9:31
1
or use the [] syntax... data[somevar] = somevalue
– Gabriel Hurley
Jul 26 '09 at 9:35
add a comment |
Just an addition to abeing's answer above. You can define a function to encapsulate the complexity of defineProperty as mentioned below.
var defineProp = function ( obj, key, value )
var config =
value: value,
writable: true,
enumerable: true,
configurable: true
;
Object.defineProperty( obj, key, config );
;
//Call the method to add properties to any object
defineProp( data, "PropertyA", 1 );
defineProp( data, "PropertyB", 2 );
defineProp( data, "PropertyC", 3 );
reference: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript
add a comment |
You can add properties dynamically using some of the options below:
In you example:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
You can define a property with a dynamic value in the next two ways:
data.key = value;
or
data['key'] = value;
Even more..if your key is also dynamic you can define using the Object class with:
Object.defineProperty(data, key, withValue(value));
where data is your object, key is the variable to store the key name and value is the variable to store the value.
I hope this helps!
add a comment |
I know there are several answers to this post already, but I haven't seen one wherein there are multiple properties and they are within an array. And this solution by the way is for ES6.
For illustration, let's say we have an array named person with objects inside:
let Person = [id:1, Name: "John", id:2, Name: "Susan", id:3, Name: "Jet"]
So, you can add a property with corresponding value. Let's say we want to add a Language with a default value of EN.
Person.map((obj)=>(...obj,['Language']:"EN"))
The Person array now would become like this:
Person = [id:1, Name: "John", Language:"EN",
id:2, Name: "Susan", Language:"EN", id:3, Name: "Jet", Language:"EN"]
You're not actually adding properties to an object, you're creating a new object with the old object's properties (via spread operator) and the new props as well.
– Ed Orsi
Nov 10 '17 at 20:22
2
You're right on that it should have beenPerson = Person.map(code here)
. But the point is you can add property to an existing object easily withES6
.
– Edper
Nov 10 '17 at 23:27
add a comment |
The simplest and most portable way is.
var varFieldName = "good";
var ob = ;
Object.defineProperty(ob, varFieldName , value: "Fresh Value" );
Based on #abeing answer!
add a comment |
ES6 introduces computed property names, which allow you to do
let a = 'key'
let myObj = [a]: 10;
// output will be key:10
add a comment |
A nice way to access from dynamic string names that contain objects (for example object.subobject.property)
function ReadValue(varname)
var v=varname.split(".");
var o=window;
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
return o[v[v.length-1]];
function AssignValue(varname,value)
var v=varname.split(".");
var o=window;
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
o[v[v.length-1]]=value;
Example:
ReadValue("object.subobject.property");
WriteValue("object.subobject.property",5);
eval works for read value, but write value is a bit harder.
A more advanced version (Create subclasses if they dont exists, and allows objects instead of global variables)
function ReadValue(varname,o=window)
if(typeof(varname)==="undefined"
function AssignValue(varname,value,o=window)
typeof(o)==="undefined"
Example:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
This is the same that o.object.subobject.property
1
exactly what I was looking for, this is useful for react this.setState(dynamic property: value ) thankyou!
– Kevin Danikowski
Apr 7 '18 at 5:36
add a comment |
Be careful while adding a property to the existing object using .(dot) method.
(.dot) method of adding a property to the object should only be used if you know the 'key' beforehand otherwise use the [bracket] method.
Example:
var data =
'Property1': 1
;
// Two methods of adding a new property [ key (Property4), value (4) ] to the
// existing object (data)
data['Property2'] = 2; // bracket method
data.Property3 = 3; // dot method
console.log(data); // Property1: 1, Property2: 2, Property3: 3
// But if 'key' of a property is unknown and will be found / calculated
// dynamically then use only [bracket] method not a dot method
var key;
for(var i = 4; i < 6; ++i)
key = 'Property' + i; // Key - dynamically calculated
data[key] = i; // CORRECT !!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5
for(var i = 6; i < 2000; ++i)
key = 'Property' + i; // Key - dynamically calculated
data.key = i; // WRONG !!!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3,
// Property4: 4, Property5: 5, key: 1999
Note the problem in the end of console log -
'key: 1999' instead of Property6: 6, Property7: 7,.........,Property1999: 1999. So the best way of adding dynamically created property is the [bracket] method.
add a comment |
Here's how I solved the problem.
var obj =
;
var field = "someouter.someinner.someValue";
var value = 123;
function _addField( obj, field, value )
// split the field into tokens
var tokens = field.split( '.' );
// if there's more than one token, this field is an object
if( tokens.length > 1 )
var subObj = tokens[0];
// define the object
if( obj[ subObj ] !== undefined ) obj[ subObj ] = ;
// call addfield again on the embedded object
var firstDot = field.indexOf( '.' );
_addField( obj[ subObj ], field.substr( firstDot + 1 ), value );
else
// no embedded objects, just field assignment
obj[ field ] = value;
_addField( obj, field, value );
_addField(obj, 'simpleString', 'string');
console.log( JSON.stringify( obj, null, 2 ) );
Generates the following object:
"someouter":
"someinner":
"someValue": 123
,
"simpleString": "string"
add a comment |
A perfect easy way
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var newProperty = 'getThisFromUser';
data[newProperty] = 4;
console.log(data);
If you want to apply it on an array of data (ES6/TS version)
const data = [
'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 ,
'PropertyA': 11, 'PropertyB': 22, 'PropertyC': 33
];
const newProperty = 'getThisFromUser';
data.map( (d) => d[newProperty] = 4 );
console.log(data);
add a comment |
Definitely. Think of it as a dictionary or associative array. You can add to it at any point.
19
I think we can assume an implicit "and if so, how?" in the question...
– Marc Gravell♦
Jul 26 '09 at 9:32
1
Just saying that will not help.
– Obinna Nwakwue
Aug 28 '16 at 14:51
add a comment |
protected by tchrist Sep 8 '12 at 15:05
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
17 Answers
17
active
oldest
votes
17 Answers
17
active
oldest
votes
active
oldest
votes
active
oldest
votes
Yes.
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
68
data.PropertyD = 4 would also work.
– thedz
Jul 26 '09 at 9:41
130
@thedz: data.PropertyD needs to know the property name, which isn't dynamic enough.
– Georg Schölly
Jul 26 '09 at 9:54
6
+1 because this helped me. But I don't understand why an object properties is handled like an array.
– Ron van der Heijden
Mar 5 '13 at 11:56
9
@Bondye: That's part of the strange design of javascript. In this caseobject["property"]
is not exactly the same asarray[4]
, the former wasn't created as a true array.
– Georg Schölly
Mar 5 '13 at 12:15
16
@Qantas: Let's say it doesn't answer it directly. But going fromdata["PropertyD"]
todata[function_to_get_property_name()]
seems trivial.
– Georg Schölly
Feb 24 '14 at 10:17
|
show 14 more comments
Yes.
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
68
data.PropertyD = 4 would also work.
– thedz
Jul 26 '09 at 9:41
130
@thedz: data.PropertyD needs to know the property name, which isn't dynamic enough.
– Georg Schölly
Jul 26 '09 at 9:54
6
+1 because this helped me. But I don't understand why an object properties is handled like an array.
– Ron van der Heijden
Mar 5 '13 at 11:56
9
@Bondye: That's part of the strange design of javascript. In this caseobject["property"]
is not exactly the same asarray[4]
, the former wasn't created as a true array.
– Georg Schölly
Mar 5 '13 at 12:15
16
@Qantas: Let's say it doesn't answer it directly. But going fromdata["PropertyD"]
todata[function_to_get_property_name()]
seems trivial.
– Georg Schölly
Feb 24 '14 at 10:17
|
show 14 more comments
Yes.
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
Yes.
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
edited Jan 8 '17 at 16:50
H. Pauwelyn
6,23621 gold badges51 silver badges95 bronze badges
6,23621 gold badges51 silver badges95 bronze badges
answered Jul 26 '09 at 9:27
Georg SchöllyGeorg Schölly
101k42 gold badges189 silver badges246 bronze badges
101k42 gold badges189 silver badges246 bronze badges
68
data.PropertyD = 4 would also work.
– thedz
Jul 26 '09 at 9:41
130
@thedz: data.PropertyD needs to know the property name, which isn't dynamic enough.
– Georg Schölly
Jul 26 '09 at 9:54
6
+1 because this helped me. But I don't understand why an object properties is handled like an array.
– Ron van der Heijden
Mar 5 '13 at 11:56
9
@Bondye: That's part of the strange design of javascript. In this caseobject["property"]
is not exactly the same asarray[4]
, the former wasn't created as a true array.
– Georg Schölly
Mar 5 '13 at 12:15
16
@Qantas: Let's say it doesn't answer it directly. But going fromdata["PropertyD"]
todata[function_to_get_property_name()]
seems trivial.
– Georg Schölly
Feb 24 '14 at 10:17
|
show 14 more comments
68
data.PropertyD = 4 would also work.
– thedz
Jul 26 '09 at 9:41
130
@thedz: data.PropertyD needs to know the property name, which isn't dynamic enough.
– Georg Schölly
Jul 26 '09 at 9:54
6
+1 because this helped me. But I don't understand why an object properties is handled like an array.
– Ron van der Heijden
Mar 5 '13 at 11:56
9
@Bondye: That's part of the strange design of javascript. In this caseobject["property"]
is not exactly the same asarray[4]
, the former wasn't created as a true array.
– Georg Schölly
Mar 5 '13 at 12:15
16
@Qantas: Let's say it doesn't answer it directly. But going fromdata["PropertyD"]
todata[function_to_get_property_name()]
seems trivial.
– Georg Schölly
Feb 24 '14 at 10:17
68
68
data.PropertyD = 4 would also work.
– thedz
Jul 26 '09 at 9:41
data.PropertyD = 4 would also work.
– thedz
Jul 26 '09 at 9:41
130
130
@thedz: data.PropertyD needs to know the property name, which isn't dynamic enough.
– Georg Schölly
Jul 26 '09 at 9:54
@thedz: data.PropertyD needs to know the property name, which isn't dynamic enough.
– Georg Schölly
Jul 26 '09 at 9:54
6
6
+1 because this helped me. But I don't understand why an object properties is handled like an array.
– Ron van der Heijden
Mar 5 '13 at 11:56
+1 because this helped me. But I don't understand why an object properties is handled like an array.
– Ron van der Heijden
Mar 5 '13 at 11:56
9
9
@Bondye: That's part of the strange design of javascript. In this case
object["property"]
is not exactly the same as array[4]
, the former wasn't created as a true array.– Georg Schölly
Mar 5 '13 at 12:15
@Bondye: That's part of the strange design of javascript. In this case
object["property"]
is not exactly the same as array[4]
, the former wasn't created as a true array.– Georg Schölly
Mar 5 '13 at 12:15
16
16
@Qantas: Let's say it doesn't answer it directly. But going from
data["PropertyD"]
to data[function_to_get_property_name()]
seems trivial.– Georg Schölly
Feb 24 '14 at 10:17
@Qantas: Let's say it doesn't answer it directly. But going from
data["PropertyD"]
to data[function_to_get_property_name()]
seems trivial.– Georg Schölly
Feb 24 '14 at 10:17
|
show 14 more comments
ES6 for the win!
const b = 'b';
const c = 'c';
const data =
a: true,
[b]: true, // dynamic property
[`interpolated-$c`]: true, // dynamic property + interpolation
[`$b-$c`]: true
If you log data
you get this:
a: true,
b: true,
interpolated-c: true,
b-c: true
This makes use of the new Computed Property syntax and Template Literals.
1
This is what I needed in the case where I wanted my code to be completely functional (as in, no imperative statements sayingobj[propname]
). Instead, I was able to use this with object spread syntax.
– intcreator
Feb 13 '18 at 5:41
1
It is not immediately obvious what this code snippet is doing to someone who hasn't seen or comprehended the new syntax. I would suggest an edit to display the output / expected properies with the 'a' const.
– Alexander Pritchard
Mar 20 '18 at 16:47
Personally, I think the ES5 way is a lot cleaner and easier to understand:var a = ; a["dynamic-" + prop] = true;
– Jack Giffin
Apr 3 '18 at 16:39
1
@JackGiffin in some cases yes, but when working with immutable structures, this syntax can be very handy, since the approach you showed is mutatinga
. (Specially when using packages like redux)
– Mauricio Soares
Aug 10 '18 at 9:35
3
This is just great ...state, [prop]: val
– Xipo
Aug 23 '18 at 14:33
|
show 1 more comment
ES6 for the win!
const b = 'b';
const c = 'c';
const data =
a: true,
[b]: true, // dynamic property
[`interpolated-$c`]: true, // dynamic property + interpolation
[`$b-$c`]: true
If you log data
you get this:
a: true,
b: true,
interpolated-c: true,
b-c: true
This makes use of the new Computed Property syntax and Template Literals.
1
This is what I needed in the case where I wanted my code to be completely functional (as in, no imperative statements sayingobj[propname]
). Instead, I was able to use this with object spread syntax.
– intcreator
Feb 13 '18 at 5:41
1
It is not immediately obvious what this code snippet is doing to someone who hasn't seen or comprehended the new syntax. I would suggest an edit to display the output / expected properies with the 'a' const.
– Alexander Pritchard
Mar 20 '18 at 16:47
Personally, I think the ES5 way is a lot cleaner and easier to understand:var a = ; a["dynamic-" + prop] = true;
– Jack Giffin
Apr 3 '18 at 16:39
1
@JackGiffin in some cases yes, but when working with immutable structures, this syntax can be very handy, since the approach you showed is mutatinga
. (Specially when using packages like redux)
– Mauricio Soares
Aug 10 '18 at 9:35
3
This is just great ...state, [prop]: val
– Xipo
Aug 23 '18 at 14:33
|
show 1 more comment
ES6 for the win!
const b = 'b';
const c = 'c';
const data =
a: true,
[b]: true, // dynamic property
[`interpolated-$c`]: true, // dynamic property + interpolation
[`$b-$c`]: true
If you log data
you get this:
a: true,
b: true,
interpolated-c: true,
b-c: true
This makes use of the new Computed Property syntax and Template Literals.
ES6 for the win!
const b = 'b';
const c = 'c';
const data =
a: true,
[b]: true, // dynamic property
[`interpolated-$c`]: true, // dynamic property + interpolation
[`$b-$c`]: true
If you log data
you get this:
a: true,
b: true,
interpolated-c: true,
b-c: true
This makes use of the new Computed Property syntax and Template Literals.
edited Sep 13 '18 at 20:51
Luca Kiebel
7,6065 gold badges17 silver badges32 bronze badges
7,6065 gold badges17 silver badges32 bronze badges
answered Feb 23 '16 at 14:11
Mauricio SoaresMauricio Soares
1,4691 gold badge11 silver badges15 bronze badges
1,4691 gold badge11 silver badges15 bronze badges
1
This is what I needed in the case where I wanted my code to be completely functional (as in, no imperative statements sayingobj[propname]
). Instead, I was able to use this with object spread syntax.
– intcreator
Feb 13 '18 at 5:41
1
It is not immediately obvious what this code snippet is doing to someone who hasn't seen or comprehended the new syntax. I would suggest an edit to display the output / expected properies with the 'a' const.
– Alexander Pritchard
Mar 20 '18 at 16:47
Personally, I think the ES5 way is a lot cleaner and easier to understand:var a = ; a["dynamic-" + prop] = true;
– Jack Giffin
Apr 3 '18 at 16:39
1
@JackGiffin in some cases yes, but when working with immutable structures, this syntax can be very handy, since the approach you showed is mutatinga
. (Specially when using packages like redux)
– Mauricio Soares
Aug 10 '18 at 9:35
3
This is just great ...state, [prop]: val
– Xipo
Aug 23 '18 at 14:33
|
show 1 more comment
1
This is what I needed in the case where I wanted my code to be completely functional (as in, no imperative statements sayingobj[propname]
). Instead, I was able to use this with object spread syntax.
– intcreator
Feb 13 '18 at 5:41
1
It is not immediately obvious what this code snippet is doing to someone who hasn't seen or comprehended the new syntax. I would suggest an edit to display the output / expected properies with the 'a' const.
– Alexander Pritchard
Mar 20 '18 at 16:47
Personally, I think the ES5 way is a lot cleaner and easier to understand:var a = ; a["dynamic-" + prop] = true;
– Jack Giffin
Apr 3 '18 at 16:39
1
@JackGiffin in some cases yes, but when working with immutable structures, this syntax can be very handy, since the approach you showed is mutatinga
. (Specially when using packages like redux)
– Mauricio Soares
Aug 10 '18 at 9:35
3
This is just great ...state, [prop]: val
– Xipo
Aug 23 '18 at 14:33
1
1
This is what I needed in the case where I wanted my code to be completely functional (as in, no imperative statements saying
obj[propname]
). Instead, I was able to use this with object spread syntax.– intcreator
Feb 13 '18 at 5:41
This is what I needed in the case where I wanted my code to be completely functional (as in, no imperative statements saying
obj[propname]
). Instead, I was able to use this with object spread syntax.– intcreator
Feb 13 '18 at 5:41
1
1
It is not immediately obvious what this code snippet is doing to someone who hasn't seen or comprehended the new syntax. I would suggest an edit to display the output / expected properies with the 'a' const.
– Alexander Pritchard
Mar 20 '18 at 16:47
It is not immediately obvious what this code snippet is doing to someone who hasn't seen or comprehended the new syntax. I would suggest an edit to display the output / expected properies with the 'a' const.
– Alexander Pritchard
Mar 20 '18 at 16:47
Personally, I think the ES5 way is a lot cleaner and easier to understand:
var a = ; a["dynamic-" + prop] = true;
– Jack Giffin
Apr 3 '18 at 16:39
Personally, I think the ES5 way is a lot cleaner and easier to understand:
var a = ; a["dynamic-" + prop] = true;
– Jack Giffin
Apr 3 '18 at 16:39
1
1
@JackGiffin in some cases yes, but when working with immutable structures, this syntax can be very handy, since the approach you showed is mutating
a
. (Specially when using packages like redux)– Mauricio Soares
Aug 10 '18 at 9:35
@JackGiffin in some cases yes, but when working with immutable structures, this syntax can be very handy, since the approach you showed is mutating
a
. (Specially when using packages like redux)– Mauricio Soares
Aug 10 '18 at 9:35
3
3
This is just great ...state, [prop]: val
– Xipo
Aug 23 '18 at 14:33
This is just great ...state, [prop]: val
– Xipo
Aug 23 '18 at 14:33
|
show 1 more comment
Yes it is possible. Assuming:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propertyName = "someProperty";
var propertyValue = "someValue";
Either:
data[propertyName] = propertyValue;
or
eval("data." + propertyName + " = '" + propertyValue + "'");
The first method is preferred. eval() has the obvious security concerns if you're using values supplied by the user so don't use it if you can avoid it but it's worth knowing it exists and what it can do.
You can reference this with:
alert(data.someProperty);
or
data(data["someProperty"]);
or
alert(data[propertyName]);
38
Using eval is really dangerous.
– Georg Schölly
Jul 26 '09 at 9:29
10
Not to mention slow.
– Eamon Nerbonne
Jul 26 '09 at 11:46
3
JQuery Extend can also be used api.jquery.com/jQuery.extend
– learnerplates
Oct 18 '12 at 11:23
@GeorgSchölly True.
– Obinna Nwakwue
Aug 28 '16 at 14:47
1
Note (in case someone runs into the same issue as I did): For normal objects this works fine. But I had to add some property to a jQuery UI object to keep track of a list of items. In that case, the property was lost if added this way because jQuery always creates a copy. Here you need to use jQuery.extend().
– Matt
Jul 7 '17 at 11:03
|
show 1 more comment
Yes it is possible. Assuming:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propertyName = "someProperty";
var propertyValue = "someValue";
Either:
data[propertyName] = propertyValue;
or
eval("data." + propertyName + " = '" + propertyValue + "'");
The first method is preferred. eval() has the obvious security concerns if you're using values supplied by the user so don't use it if you can avoid it but it's worth knowing it exists and what it can do.
You can reference this with:
alert(data.someProperty);
or
data(data["someProperty"]);
or
alert(data[propertyName]);
38
Using eval is really dangerous.
– Georg Schölly
Jul 26 '09 at 9:29
10
Not to mention slow.
– Eamon Nerbonne
Jul 26 '09 at 11:46
3
JQuery Extend can also be used api.jquery.com/jQuery.extend
– learnerplates
Oct 18 '12 at 11:23
@GeorgSchölly True.
– Obinna Nwakwue
Aug 28 '16 at 14:47
1
Note (in case someone runs into the same issue as I did): For normal objects this works fine. But I had to add some property to a jQuery UI object to keep track of a list of items. In that case, the property was lost if added this way because jQuery always creates a copy. Here you need to use jQuery.extend().
– Matt
Jul 7 '17 at 11:03
|
show 1 more comment
Yes it is possible. Assuming:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propertyName = "someProperty";
var propertyValue = "someValue";
Either:
data[propertyName] = propertyValue;
or
eval("data." + propertyName + " = '" + propertyValue + "'");
The first method is preferred. eval() has the obvious security concerns if you're using values supplied by the user so don't use it if you can avoid it but it's worth knowing it exists and what it can do.
You can reference this with:
alert(data.someProperty);
or
data(data["someProperty"]);
or
alert(data[propertyName]);
Yes it is possible. Assuming:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propertyName = "someProperty";
var propertyValue = "someValue";
Either:
data[propertyName] = propertyValue;
or
eval("data." + propertyName + " = '" + propertyValue + "'");
The first method is preferred. eval() has the obvious security concerns if you're using values supplied by the user so don't use it if you can avoid it but it's worth knowing it exists and what it can do.
You can reference this with:
alert(data.someProperty);
or
data(data["someProperty"]);
or
alert(data[propertyName]);
edited Jul 26 '09 at 9:32
answered Jul 26 '09 at 9:27
cletuscletus
522k142 gold badges850 silver badges917 bronze badges
522k142 gold badges850 silver badges917 bronze badges
38
Using eval is really dangerous.
– Georg Schölly
Jul 26 '09 at 9:29
10
Not to mention slow.
– Eamon Nerbonne
Jul 26 '09 at 11:46
3
JQuery Extend can also be used api.jquery.com/jQuery.extend
– learnerplates
Oct 18 '12 at 11:23
@GeorgSchölly True.
– Obinna Nwakwue
Aug 28 '16 at 14:47
1
Note (in case someone runs into the same issue as I did): For normal objects this works fine. But I had to add some property to a jQuery UI object to keep track of a list of items. In that case, the property was lost if added this way because jQuery always creates a copy. Here you need to use jQuery.extend().
– Matt
Jul 7 '17 at 11:03
|
show 1 more comment
38
Using eval is really dangerous.
– Georg Schölly
Jul 26 '09 at 9:29
10
Not to mention slow.
– Eamon Nerbonne
Jul 26 '09 at 11:46
3
JQuery Extend can also be used api.jquery.com/jQuery.extend
– learnerplates
Oct 18 '12 at 11:23
@GeorgSchölly True.
– Obinna Nwakwue
Aug 28 '16 at 14:47
1
Note (in case someone runs into the same issue as I did): For normal objects this works fine. But I had to add some property to a jQuery UI object to keep track of a list of items. In that case, the property was lost if added this way because jQuery always creates a copy. Here you need to use jQuery.extend().
– Matt
Jul 7 '17 at 11:03
38
38
Using eval is really dangerous.
– Georg Schölly
Jul 26 '09 at 9:29
Using eval is really dangerous.
– Georg Schölly
Jul 26 '09 at 9:29
10
10
Not to mention slow.
– Eamon Nerbonne
Jul 26 '09 at 11:46
Not to mention slow.
– Eamon Nerbonne
Jul 26 '09 at 11:46
3
3
JQuery Extend can also be used api.jquery.com/jQuery.extend
– learnerplates
Oct 18 '12 at 11:23
JQuery Extend can also be used api.jquery.com/jQuery.extend
– learnerplates
Oct 18 '12 at 11:23
@GeorgSchölly True.
– Obinna Nwakwue
Aug 28 '16 at 14:47
@GeorgSchölly True.
– Obinna Nwakwue
Aug 28 '16 at 14:47
1
1
Note (in case someone runs into the same issue as I did): For normal objects this works fine. But I had to add some property to a jQuery UI object to keep track of a list of items. In that case, the property was lost if added this way because jQuery always creates a copy. Here you need to use jQuery.extend().
– Matt
Jul 7 '17 at 11:03
Note (in case someone runs into the same issue as I did): For normal objects this works fine. But I had to add some property to a jQuery UI object to keep track of a list of items. In that case, the property was lost if added this way because jQuery always creates a copy. Here you need to use jQuery.extend().
– Matt
Jul 7 '17 at 11:03
|
show 1 more comment
I know that the question is answered perfectly, but I also found another way to add new properties and wanted to share it with you:
You can use the function Object.defineProperty()
Found on Mozilla Developer Network
Example:
var o = ; // Creates a new object
// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", value : 37,
writable : true,
enumerable : true,
configurable : true);
// 'a' property exists in the o object and its value is 37
// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", get : function() return bValue; ,
set : function(newValue) bValue = newValue; ,
enumerable : true,
configurable : true);
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined
// You cannot try to mix both :
Object.defineProperty(o, "conflict", value: 0x9f91102,
get: function() return 0xdeadbeef; );
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
4
Pros and cons of this method?
– Trevor
Jan 14 '14 at 21:06
5
@Trevor: Total configurability and ability to add getters and setters; also, ability to add multiple properties at once withdefineProperties
(plural).
– rvighne
Aug 10 '14 at 1:08
@ThieliciousObject.defineProperty
isn’t meant to be the easy convenience tool, but the one with the fine-grained control. If you don’t need that additional control, it’s not the right tool to choose.
– kleinfreund
Sep 6 '17 at 9:00
Object.defineProperty(obj, prop, valueDescriptor)
is a lot slower and harder for V8 to optimize than simply doingobj[prop] = value
;
– Jack Giffin
Apr 3 '18 at 16:37
add a comment |
I know that the question is answered perfectly, but I also found another way to add new properties and wanted to share it with you:
You can use the function Object.defineProperty()
Found on Mozilla Developer Network
Example:
var o = ; // Creates a new object
// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", value : 37,
writable : true,
enumerable : true,
configurable : true);
// 'a' property exists in the o object and its value is 37
// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", get : function() return bValue; ,
set : function(newValue) bValue = newValue; ,
enumerable : true,
configurable : true);
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined
// You cannot try to mix both :
Object.defineProperty(o, "conflict", value: 0x9f91102,
get: function() return 0xdeadbeef; );
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
4
Pros and cons of this method?
– Trevor
Jan 14 '14 at 21:06
5
@Trevor: Total configurability and ability to add getters and setters; also, ability to add multiple properties at once withdefineProperties
(plural).
– rvighne
Aug 10 '14 at 1:08
@ThieliciousObject.defineProperty
isn’t meant to be the easy convenience tool, but the one with the fine-grained control. If you don’t need that additional control, it’s not the right tool to choose.
– kleinfreund
Sep 6 '17 at 9:00
Object.defineProperty(obj, prop, valueDescriptor)
is a lot slower and harder for V8 to optimize than simply doingobj[prop] = value
;
– Jack Giffin
Apr 3 '18 at 16:37
add a comment |
I know that the question is answered perfectly, but I also found another way to add new properties and wanted to share it with you:
You can use the function Object.defineProperty()
Found on Mozilla Developer Network
Example:
var o = ; // Creates a new object
// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", value : 37,
writable : true,
enumerable : true,
configurable : true);
// 'a' property exists in the o object and its value is 37
// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", get : function() return bValue; ,
set : function(newValue) bValue = newValue; ,
enumerable : true,
configurable : true);
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined
// You cannot try to mix both :
Object.defineProperty(o, "conflict", value: 0x9f91102,
get: function() return 0xdeadbeef; );
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
I know that the question is answered perfectly, but I also found another way to add new properties and wanted to share it with you:
You can use the function Object.defineProperty()
Found on Mozilla Developer Network
Example:
var o = ; // Creates a new object
// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", value : 37,
writable : true,
enumerable : true,
configurable : true);
// 'a' property exists in the o object and its value is 37
// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", get : function() return bValue; ,
set : function(newValue) bValue = newValue; ,
enumerable : true,
configurable : true);
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined
// You cannot try to mix both :
Object.defineProperty(o, "conflict", value: 0x9f91102,
get: function() return 0xdeadbeef; );
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
answered Aug 15 '13 at 8:41
artgroheartgrohe
93012 silver badges24 bronze badges
93012 silver badges24 bronze badges
4
Pros and cons of this method?
– Trevor
Jan 14 '14 at 21:06
5
@Trevor: Total configurability and ability to add getters and setters; also, ability to add multiple properties at once withdefineProperties
(plural).
– rvighne
Aug 10 '14 at 1:08
@ThieliciousObject.defineProperty
isn’t meant to be the easy convenience tool, but the one with the fine-grained control. If you don’t need that additional control, it’s not the right tool to choose.
– kleinfreund
Sep 6 '17 at 9:00
Object.defineProperty(obj, prop, valueDescriptor)
is a lot slower and harder for V8 to optimize than simply doingobj[prop] = value
;
– Jack Giffin
Apr 3 '18 at 16:37
add a comment |
4
Pros and cons of this method?
– Trevor
Jan 14 '14 at 21:06
5
@Trevor: Total configurability and ability to add getters and setters; also, ability to add multiple properties at once withdefineProperties
(plural).
– rvighne
Aug 10 '14 at 1:08
@ThieliciousObject.defineProperty
isn’t meant to be the easy convenience tool, but the one with the fine-grained control. If you don’t need that additional control, it’s not the right tool to choose.
– kleinfreund
Sep 6 '17 at 9:00
Object.defineProperty(obj, prop, valueDescriptor)
is a lot slower and harder for V8 to optimize than simply doingobj[prop] = value
;
– Jack Giffin
Apr 3 '18 at 16:37
4
4
Pros and cons of this method?
– Trevor
Jan 14 '14 at 21:06
Pros and cons of this method?
– Trevor
Jan 14 '14 at 21:06
5
5
@Trevor: Total configurability and ability to add getters and setters; also, ability to add multiple properties at once with
defineProperties
(plural).– rvighne
Aug 10 '14 at 1:08
@Trevor: Total configurability and ability to add getters and setters; also, ability to add multiple properties at once with
defineProperties
(plural).– rvighne
Aug 10 '14 at 1:08
@Thielicious
Object.defineProperty
isn’t meant to be the easy convenience tool, but the one with the fine-grained control. If you don’t need that additional control, it’s not the right tool to choose.– kleinfreund
Sep 6 '17 at 9:00
@Thielicious
Object.defineProperty
isn’t meant to be the easy convenience tool, but the one with the fine-grained control. If you don’t need that additional control, it’s not the right tool to choose.– kleinfreund
Sep 6 '17 at 9:00
Object.defineProperty(obj, prop, valueDescriptor)
is a lot slower and harder for V8 to optimize than simply doing obj[prop] = value
;– Jack Giffin
Apr 3 '18 at 16:37
Object.defineProperty(obj, prop, valueDescriptor)
is a lot slower and harder for V8 to optimize than simply doing obj[prop] = value
;– Jack Giffin
Apr 3 '18 at 16:37
add a comment |
Here, using your notation:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
data[propName] = 'Some New Property value'
add a comment |
Here, using your notation:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
data[propName] = 'Some New Property value'
add a comment |
Here, using your notation:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
data[propName] = 'Some New Property value'
Here, using your notation:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
data[propName] = 'Some New Property value'
answered Jul 26 '09 at 9:34
Maxim SloykoMaxim Sloyko
9,9804 gold badges32 silver badges45 bronze badges
9,9804 gold badges32 silver badges45 bronze badges
add a comment |
add a comment |
in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:
var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex =
[ personId ]: person
// ^ computed property name
;
personIndex[ personId ]; // "John Doe"
reference: Understanding ECMAScript 6 - Nickolas Zakas
add a comment |
in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:
var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex =
[ personId ]: person
// ^ computed property name
;
personIndex[ personId ]; // "John Doe"
reference: Understanding ECMAScript 6 - Nickolas Zakas
add a comment |
in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:
var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex =
[ personId ]: person
// ^ computed property name
;
personIndex[ personId ]; // "John Doe"
reference: Understanding ECMAScript 6 - Nickolas Zakas
in addition to all the previous answers, and in case you're wondering how we're going to write dynamic property names in the Future using Computed Property Names ( ECMAScript 6 ), here's how:
var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex =
[ personId ]: person
// ^ computed property name
;
personIndex[ personId ]; // "John Doe"
reference: Understanding ECMAScript 6 - Nickolas Zakas
answered Apr 1 '14 at 10:49
Anas NakawaAnas Nakawa
1,31918 silver badges40 bronze badges
1,31918 silver badges40 bronze badges
add a comment |
add a comment |
You can add as many more properties as you like simply by using the dot notation:
var data =
var1:'somevalue'
data.newAttribute = 'newvalue'
or:
data[newattribute] = somevalue
for dynamic keys.
3
if the properties name is not determined until run time" - so that won't work unless you use eval, which isn't a good option
– Marc Gravell♦
Jul 26 '09 at 9:31
1
or use the [] syntax... data[somevar] = somevalue
– Gabriel Hurley
Jul 26 '09 at 9:35
add a comment |
You can add as many more properties as you like simply by using the dot notation:
var data =
var1:'somevalue'
data.newAttribute = 'newvalue'
or:
data[newattribute] = somevalue
for dynamic keys.
3
if the properties name is not determined until run time" - so that won't work unless you use eval, which isn't a good option
– Marc Gravell♦
Jul 26 '09 at 9:31
1
or use the [] syntax... data[somevar] = somevalue
– Gabriel Hurley
Jul 26 '09 at 9:35
add a comment |
You can add as many more properties as you like simply by using the dot notation:
var data =
var1:'somevalue'
data.newAttribute = 'newvalue'
or:
data[newattribute] = somevalue
for dynamic keys.
You can add as many more properties as you like simply by using the dot notation:
var data =
var1:'somevalue'
data.newAttribute = 'newvalue'
or:
data[newattribute] = somevalue
for dynamic keys.
edited Jul 26 '09 at 9:37
answered Jul 26 '09 at 9:28
Gabriel HurleyGabriel Hurley
33.8k11 gold badges52 silver badges82 bronze badges
33.8k11 gold badges52 silver badges82 bronze badges
3
if the properties name is not determined until run time" - so that won't work unless you use eval, which isn't a good option
– Marc Gravell♦
Jul 26 '09 at 9:31
1
or use the [] syntax... data[somevar] = somevalue
– Gabriel Hurley
Jul 26 '09 at 9:35
add a comment |
3
if the properties name is not determined until run time" - so that won't work unless you use eval, which isn't a good option
– Marc Gravell♦
Jul 26 '09 at 9:31
1
or use the [] syntax... data[somevar] = somevalue
– Gabriel Hurley
Jul 26 '09 at 9:35
3
3
if the properties name is not determined until run time" - so that won't work unless you use eval, which isn't a good option
– Marc Gravell♦
Jul 26 '09 at 9:31
if the properties name is not determined until run time" - so that won't work unless you use eval, which isn't a good option
– Marc Gravell♦
Jul 26 '09 at 9:31
1
1
or use the [] syntax... data[somevar] = somevalue
– Gabriel Hurley
Jul 26 '09 at 9:35
or use the [] syntax... data[somevar] = somevalue
– Gabriel Hurley
Jul 26 '09 at 9:35
add a comment |
Just an addition to abeing's answer above. You can define a function to encapsulate the complexity of defineProperty as mentioned below.
var defineProp = function ( obj, key, value )
var config =
value: value,
writable: true,
enumerable: true,
configurable: true
;
Object.defineProperty( obj, key, config );
;
//Call the method to add properties to any object
defineProp( data, "PropertyA", 1 );
defineProp( data, "PropertyB", 2 );
defineProp( data, "PropertyC", 3 );
reference: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript
add a comment |
Just an addition to abeing's answer above. You can define a function to encapsulate the complexity of defineProperty as mentioned below.
var defineProp = function ( obj, key, value )
var config =
value: value,
writable: true,
enumerable: true,
configurable: true
;
Object.defineProperty( obj, key, config );
;
//Call the method to add properties to any object
defineProp( data, "PropertyA", 1 );
defineProp( data, "PropertyB", 2 );
defineProp( data, "PropertyC", 3 );
reference: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript
add a comment |
Just an addition to abeing's answer above. You can define a function to encapsulate the complexity of defineProperty as mentioned below.
var defineProp = function ( obj, key, value )
var config =
value: value,
writable: true,
enumerable: true,
configurable: true
;
Object.defineProperty( obj, key, config );
;
//Call the method to add properties to any object
defineProp( data, "PropertyA", 1 );
defineProp( data, "PropertyB", 2 );
defineProp( data, "PropertyC", 3 );
reference: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript
Just an addition to abeing's answer above. You can define a function to encapsulate the complexity of defineProperty as mentioned below.
var defineProp = function ( obj, key, value )
var config =
value: value,
writable: true,
enumerable: true,
configurable: true
;
Object.defineProperty( obj, key, config );
;
//Call the method to add properties to any object
defineProp( data, "PropertyA", 1 );
defineProp( data, "PropertyB", 2 );
defineProp( data, "PropertyC", 3 );
reference: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript
answered Apr 8 '14 at 5:24
SarveshSarvesh
4178 silver badges16 bronze badges
4178 silver badges16 bronze badges
add a comment |
add a comment |
You can add properties dynamically using some of the options below:
In you example:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
You can define a property with a dynamic value in the next two ways:
data.key = value;
or
data['key'] = value;
Even more..if your key is also dynamic you can define using the Object class with:
Object.defineProperty(data, key, withValue(value));
where data is your object, key is the variable to store the key name and value is the variable to store the value.
I hope this helps!
add a comment |
You can add properties dynamically using some of the options below:
In you example:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
You can define a property with a dynamic value in the next two ways:
data.key = value;
or
data['key'] = value;
Even more..if your key is also dynamic you can define using the Object class with:
Object.defineProperty(data, key, withValue(value));
where data is your object, key is the variable to store the key name and value is the variable to store the value.
I hope this helps!
add a comment |
You can add properties dynamically using some of the options below:
In you example:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
You can define a property with a dynamic value in the next two ways:
data.key = value;
or
data['key'] = value;
Even more..if your key is also dynamic you can define using the Object class with:
Object.defineProperty(data, key, withValue(value));
where data is your object, key is the variable to store the key name and value is the variable to store the value.
I hope this helps!
You can add properties dynamically using some of the options below:
In you example:
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
You can define a property with a dynamic value in the next two ways:
data.key = value;
or
data['key'] = value;
Even more..if your key is also dynamic you can define using the Object class with:
Object.defineProperty(data, key, withValue(value));
where data is your object, key is the variable to store the key name and value is the variable to store the value.
I hope this helps!
edited Aug 16 '17 at 19:45
morewry
3,2502 gold badges26 silver badges32 bronze badges
3,2502 gold badges26 silver badges32 bronze badges
answered Nov 12 '15 at 14:34
FabricioFabricio
1,63711 silver badges17 bronze badges
1,63711 silver badges17 bronze badges
add a comment |
add a comment |
I know there are several answers to this post already, but I haven't seen one wherein there are multiple properties and they are within an array. And this solution by the way is for ES6.
For illustration, let's say we have an array named person with objects inside:
let Person = [id:1, Name: "John", id:2, Name: "Susan", id:3, Name: "Jet"]
So, you can add a property with corresponding value. Let's say we want to add a Language with a default value of EN.
Person.map((obj)=>(...obj,['Language']:"EN"))
The Person array now would become like this:
Person = [id:1, Name: "John", Language:"EN",
id:2, Name: "Susan", Language:"EN", id:3, Name: "Jet", Language:"EN"]
You're not actually adding properties to an object, you're creating a new object with the old object's properties (via spread operator) and the new props as well.
– Ed Orsi
Nov 10 '17 at 20:22
2
You're right on that it should have beenPerson = Person.map(code here)
. But the point is you can add property to an existing object easily withES6
.
– Edper
Nov 10 '17 at 23:27
add a comment |
I know there are several answers to this post already, but I haven't seen one wherein there are multiple properties and they are within an array. And this solution by the way is for ES6.
For illustration, let's say we have an array named person with objects inside:
let Person = [id:1, Name: "John", id:2, Name: "Susan", id:3, Name: "Jet"]
So, you can add a property with corresponding value. Let's say we want to add a Language with a default value of EN.
Person.map((obj)=>(...obj,['Language']:"EN"))
The Person array now would become like this:
Person = [id:1, Name: "John", Language:"EN",
id:2, Name: "Susan", Language:"EN", id:3, Name: "Jet", Language:"EN"]
You're not actually adding properties to an object, you're creating a new object with the old object's properties (via spread operator) and the new props as well.
– Ed Orsi
Nov 10 '17 at 20:22
2
You're right on that it should have beenPerson = Person.map(code here)
. But the point is you can add property to an existing object easily withES6
.
– Edper
Nov 10 '17 at 23:27
add a comment |
I know there are several answers to this post already, but I haven't seen one wherein there are multiple properties and they are within an array. And this solution by the way is for ES6.
For illustration, let's say we have an array named person with objects inside:
let Person = [id:1, Name: "John", id:2, Name: "Susan", id:3, Name: "Jet"]
So, you can add a property with corresponding value. Let's say we want to add a Language with a default value of EN.
Person.map((obj)=>(...obj,['Language']:"EN"))
The Person array now would become like this:
Person = [id:1, Name: "John", Language:"EN",
id:2, Name: "Susan", Language:"EN", id:3, Name: "Jet", Language:"EN"]
I know there are several answers to this post already, but I haven't seen one wherein there are multiple properties and they are within an array. And this solution by the way is for ES6.
For illustration, let's say we have an array named person with objects inside:
let Person = [id:1, Name: "John", id:2, Name: "Susan", id:3, Name: "Jet"]
So, you can add a property with corresponding value. Let's say we want to add a Language with a default value of EN.
Person.map((obj)=>(...obj,['Language']:"EN"))
The Person array now would become like this:
Person = [id:1, Name: "John", Language:"EN",
id:2, Name: "Susan", Language:"EN", id:3, Name: "Jet", Language:"EN"]
answered Oct 1 '17 at 12:41
EdperEdper
7,4421 gold badge21 silver badges44 bronze badges
7,4421 gold badge21 silver badges44 bronze badges
You're not actually adding properties to an object, you're creating a new object with the old object's properties (via spread operator) and the new props as well.
– Ed Orsi
Nov 10 '17 at 20:22
2
You're right on that it should have beenPerson = Person.map(code here)
. But the point is you can add property to an existing object easily withES6
.
– Edper
Nov 10 '17 at 23:27
add a comment |
You're not actually adding properties to an object, you're creating a new object with the old object's properties (via spread operator) and the new props as well.
– Ed Orsi
Nov 10 '17 at 20:22
2
You're right on that it should have beenPerson = Person.map(code here)
. But the point is you can add property to an existing object easily withES6
.
– Edper
Nov 10 '17 at 23:27
You're not actually adding properties to an object, you're creating a new object with the old object's properties (via spread operator) and the new props as well.
– Ed Orsi
Nov 10 '17 at 20:22
You're not actually adding properties to an object, you're creating a new object with the old object's properties (via spread operator) and the new props as well.
– Ed Orsi
Nov 10 '17 at 20:22
2
2
You're right on that it should have been
Person = Person.map(code here)
. But the point is you can add property to an existing object easily with ES6
.– Edper
Nov 10 '17 at 23:27
You're right on that it should have been
Person = Person.map(code here)
. But the point is you can add property to an existing object easily with ES6
.– Edper
Nov 10 '17 at 23:27
add a comment |
The simplest and most portable way is.
var varFieldName = "good";
var ob = ;
Object.defineProperty(ob, varFieldName , value: "Fresh Value" );
Based on #abeing answer!
add a comment |
The simplest and most portable way is.
var varFieldName = "good";
var ob = ;
Object.defineProperty(ob, varFieldName , value: "Fresh Value" );
Based on #abeing answer!
add a comment |
The simplest and most portable way is.
var varFieldName = "good";
var ob = ;
Object.defineProperty(ob, varFieldName , value: "Fresh Value" );
Based on #abeing answer!
The simplest and most portable way is.
var varFieldName = "good";
var ob = ;
Object.defineProperty(ob, varFieldName , value: "Fresh Value" );
Based on #abeing answer!
answered Mar 30 '16 at 11:23
SydwellSydwell
4,2281 gold badge24 silver badges36 bronze badges
4,2281 gold badge24 silver badges36 bronze badges
add a comment |
add a comment |
ES6 introduces computed property names, which allow you to do
let a = 'key'
let myObj = [a]: 10;
// output will be key:10
add a comment |
ES6 introduces computed property names, which allow you to do
let a = 'key'
let myObj = [a]: 10;
// output will be key:10
add a comment |
ES6 introduces computed property names, which allow you to do
let a = 'key'
let myObj = [a]: 10;
// output will be key:10
ES6 introduces computed property names, which allow you to do
let a = 'key'
let myObj = [a]: 10;
// output will be key:10
answered May 13 at 4:56
RustyRusty
1,1851 gold badge14 silver badges24 bronze badges
1,1851 gold badge14 silver badges24 bronze badges
add a comment |
add a comment |
A nice way to access from dynamic string names that contain objects (for example object.subobject.property)
function ReadValue(varname)
var v=varname.split(".");
var o=window;
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
return o[v[v.length-1]];
function AssignValue(varname,value)
var v=varname.split(".");
var o=window;
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
o[v[v.length-1]]=value;
Example:
ReadValue("object.subobject.property");
WriteValue("object.subobject.property",5);
eval works for read value, but write value is a bit harder.
A more advanced version (Create subclasses if they dont exists, and allows objects instead of global variables)
function ReadValue(varname,o=window)
if(typeof(varname)==="undefined"
function AssignValue(varname,value,o=window)
typeof(o)==="undefined"
Example:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
This is the same that o.object.subobject.property
1
exactly what I was looking for, this is useful for react this.setState(dynamic property: value ) thankyou!
– Kevin Danikowski
Apr 7 '18 at 5:36
add a comment |
A nice way to access from dynamic string names that contain objects (for example object.subobject.property)
function ReadValue(varname)
var v=varname.split(".");
var o=window;
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
return o[v[v.length-1]];
function AssignValue(varname,value)
var v=varname.split(".");
var o=window;
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
o[v[v.length-1]]=value;
Example:
ReadValue("object.subobject.property");
WriteValue("object.subobject.property",5);
eval works for read value, but write value is a bit harder.
A more advanced version (Create subclasses if they dont exists, and allows objects instead of global variables)
function ReadValue(varname,o=window)
if(typeof(varname)==="undefined"
function AssignValue(varname,value,o=window)
typeof(o)==="undefined"
Example:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
This is the same that o.object.subobject.property
1
exactly what I was looking for, this is useful for react this.setState(dynamic property: value ) thankyou!
– Kevin Danikowski
Apr 7 '18 at 5:36
add a comment |
A nice way to access from dynamic string names that contain objects (for example object.subobject.property)
function ReadValue(varname)
var v=varname.split(".");
var o=window;
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
return o[v[v.length-1]];
function AssignValue(varname,value)
var v=varname.split(".");
var o=window;
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
o[v[v.length-1]]=value;
Example:
ReadValue("object.subobject.property");
WriteValue("object.subobject.property",5);
eval works for read value, but write value is a bit harder.
A more advanced version (Create subclasses if they dont exists, and allows objects instead of global variables)
function ReadValue(varname,o=window)
if(typeof(varname)==="undefined"
function AssignValue(varname,value,o=window)
typeof(o)==="undefined"
Example:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
This is the same that o.object.subobject.property
A nice way to access from dynamic string names that contain objects (for example object.subobject.property)
function ReadValue(varname)
var v=varname.split(".");
var o=window;
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
return o[v[v.length-1]];
function AssignValue(varname,value)
var v=varname.split(".");
var o=window;
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
o=o[v[i]];
o[v[v.length-1]]=value;
Example:
ReadValue("object.subobject.property");
WriteValue("object.subobject.property",5);
eval works for read value, but write value is a bit harder.
A more advanced version (Create subclasses if they dont exists, and allows objects instead of global variables)
function ReadValue(varname,o=window)
if(typeof(varname)==="undefined"
function AssignValue(varname,value,o=window)
typeof(o)==="undefined"
Example:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
This is the same that o.object.subobject.property
edited Jun 15 '17 at 20:18
answered Jun 7 '17 at 7:51
hamboy75hamboy75
3522 silver badges14 bronze badges
3522 silver badges14 bronze badges
1
exactly what I was looking for, this is useful for react this.setState(dynamic property: value ) thankyou!
– Kevin Danikowski
Apr 7 '18 at 5:36
add a comment |
1
exactly what I was looking for, this is useful for react this.setState(dynamic property: value ) thankyou!
– Kevin Danikowski
Apr 7 '18 at 5:36
1
1
exactly what I was looking for, this is useful for react this.setState(dynamic property: value ) thankyou!
– Kevin Danikowski
Apr 7 '18 at 5:36
exactly what I was looking for, this is useful for react this.setState(dynamic property: value ) thankyou!
– Kevin Danikowski
Apr 7 '18 at 5:36
add a comment |
Be careful while adding a property to the existing object using .(dot) method.
(.dot) method of adding a property to the object should only be used if you know the 'key' beforehand otherwise use the [bracket] method.
Example:
var data =
'Property1': 1
;
// Two methods of adding a new property [ key (Property4), value (4) ] to the
// existing object (data)
data['Property2'] = 2; // bracket method
data.Property3 = 3; // dot method
console.log(data); // Property1: 1, Property2: 2, Property3: 3
// But if 'key' of a property is unknown and will be found / calculated
// dynamically then use only [bracket] method not a dot method
var key;
for(var i = 4; i < 6; ++i)
key = 'Property' + i; // Key - dynamically calculated
data[key] = i; // CORRECT !!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5
for(var i = 6; i < 2000; ++i)
key = 'Property' + i; // Key - dynamically calculated
data.key = i; // WRONG !!!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3,
// Property4: 4, Property5: 5, key: 1999
Note the problem in the end of console log -
'key: 1999' instead of Property6: 6, Property7: 7,.........,Property1999: 1999. So the best way of adding dynamically created property is the [bracket] method.
add a comment |
Be careful while adding a property to the existing object using .(dot) method.
(.dot) method of adding a property to the object should only be used if you know the 'key' beforehand otherwise use the [bracket] method.
Example:
var data =
'Property1': 1
;
// Two methods of adding a new property [ key (Property4), value (4) ] to the
// existing object (data)
data['Property2'] = 2; // bracket method
data.Property3 = 3; // dot method
console.log(data); // Property1: 1, Property2: 2, Property3: 3
// But if 'key' of a property is unknown and will be found / calculated
// dynamically then use only [bracket] method not a dot method
var key;
for(var i = 4; i < 6; ++i)
key = 'Property' + i; // Key - dynamically calculated
data[key] = i; // CORRECT !!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5
for(var i = 6; i < 2000; ++i)
key = 'Property' + i; // Key - dynamically calculated
data.key = i; // WRONG !!!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3,
// Property4: 4, Property5: 5, key: 1999
Note the problem in the end of console log -
'key: 1999' instead of Property6: 6, Property7: 7,.........,Property1999: 1999. So the best way of adding dynamically created property is the [bracket] method.
add a comment |
Be careful while adding a property to the existing object using .(dot) method.
(.dot) method of adding a property to the object should only be used if you know the 'key' beforehand otherwise use the [bracket] method.
Example:
var data =
'Property1': 1
;
// Two methods of adding a new property [ key (Property4), value (4) ] to the
// existing object (data)
data['Property2'] = 2; // bracket method
data.Property3 = 3; // dot method
console.log(data); // Property1: 1, Property2: 2, Property3: 3
// But if 'key' of a property is unknown and will be found / calculated
// dynamically then use only [bracket] method not a dot method
var key;
for(var i = 4; i < 6; ++i)
key = 'Property' + i; // Key - dynamically calculated
data[key] = i; // CORRECT !!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5
for(var i = 6; i < 2000; ++i)
key = 'Property' + i; // Key - dynamically calculated
data.key = i; // WRONG !!!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3,
// Property4: 4, Property5: 5, key: 1999
Note the problem in the end of console log -
'key: 1999' instead of Property6: 6, Property7: 7,.........,Property1999: 1999. So the best way of adding dynamically created property is the [bracket] method.
Be careful while adding a property to the existing object using .(dot) method.
(.dot) method of adding a property to the object should only be used if you know the 'key' beforehand otherwise use the [bracket] method.
Example:
var data =
'Property1': 1
;
// Two methods of adding a new property [ key (Property4), value (4) ] to the
// existing object (data)
data['Property2'] = 2; // bracket method
data.Property3 = 3; // dot method
console.log(data); // Property1: 1, Property2: 2, Property3: 3
// But if 'key' of a property is unknown and will be found / calculated
// dynamically then use only [bracket] method not a dot method
var key;
for(var i = 4; i < 6; ++i)
key = 'Property' + i; // Key - dynamically calculated
data[key] = i; // CORRECT !!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5
for(var i = 6; i < 2000; ++i)
key = 'Property' + i; // Key - dynamically calculated
data.key = i; // WRONG !!!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3,
// Property4: 4, Property5: 5, key: 1999
Note the problem in the end of console log -
'key: 1999' instead of Property6: 6, Property7: 7,.........,Property1999: 1999. So the best way of adding dynamically created property is the [bracket] method.
var data =
'Property1': 1
;
// Two methods of adding a new property [ key (Property4), value (4) ] to the
// existing object (data)
data['Property2'] = 2; // bracket method
data.Property3 = 3; // dot method
console.log(data); // Property1: 1, Property2: 2, Property3: 3
// But if 'key' of a property is unknown and will be found / calculated
// dynamically then use only [bracket] method not a dot method
var key;
for(var i = 4; i < 6; ++i)
key = 'Property' + i; // Key - dynamically calculated
data[key] = i; // CORRECT !!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5
for(var i = 6; i < 2000; ++i)
key = 'Property' + i; // Key - dynamically calculated
data.key = i; // WRONG !!!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3,
// Property4: 4, Property5: 5, key: 1999
var data =
'Property1': 1
;
// Two methods of adding a new property [ key (Property4), value (4) ] to the
// existing object (data)
data['Property2'] = 2; // bracket method
data.Property3 = 3; // dot method
console.log(data); // Property1: 1, Property2: 2, Property3: 3
// But if 'key' of a property is unknown and will be found / calculated
// dynamically then use only [bracket] method not a dot method
var key;
for(var i = 4; i < 6; ++i)
key = 'Property' + i; // Key - dynamically calculated
data[key] = i; // CORRECT !!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5
for(var i = 6; i < 2000; ++i)
key = 'Property' + i; // Key - dynamically calculated
data.key = i; // WRONG !!!!!
console.log(data);
// Property1: 1, Property2: 2, Property3: 3,
// Property4: 4, Property5: 5, key: 1999
edited Dec 11 '18 at 13:26
Eugen Konkov
7,2963 gold badges45 silver badges68 bronze badges
7,2963 gold badges45 silver badges68 bronze badges
answered Dec 7 '18 at 16:53
SridharKrithaSridharKritha
2,9031 gold badge25 silver badges26 bronze badges
2,9031 gold badge25 silver badges26 bronze badges
add a comment |
add a comment |
Here's how I solved the problem.
var obj =
;
var field = "someouter.someinner.someValue";
var value = 123;
function _addField( obj, field, value )
// split the field into tokens
var tokens = field.split( '.' );
// if there's more than one token, this field is an object
if( tokens.length > 1 )
var subObj = tokens[0];
// define the object
if( obj[ subObj ] !== undefined ) obj[ subObj ] = ;
// call addfield again on the embedded object
var firstDot = field.indexOf( '.' );
_addField( obj[ subObj ], field.substr( firstDot + 1 ), value );
else
// no embedded objects, just field assignment
obj[ field ] = value;
_addField( obj, field, value );
_addField(obj, 'simpleString', 'string');
console.log( JSON.stringify( obj, null, 2 ) );
Generates the following object:
"someouter":
"someinner":
"someValue": 123
,
"simpleString": "string"
add a comment |
Here's how I solved the problem.
var obj =
;
var field = "someouter.someinner.someValue";
var value = 123;
function _addField( obj, field, value )
// split the field into tokens
var tokens = field.split( '.' );
// if there's more than one token, this field is an object
if( tokens.length > 1 )
var subObj = tokens[0];
// define the object
if( obj[ subObj ] !== undefined ) obj[ subObj ] = ;
// call addfield again on the embedded object
var firstDot = field.indexOf( '.' );
_addField( obj[ subObj ], field.substr( firstDot + 1 ), value );
else
// no embedded objects, just field assignment
obj[ field ] = value;
_addField( obj, field, value );
_addField(obj, 'simpleString', 'string');
console.log( JSON.stringify( obj, null, 2 ) );
Generates the following object:
"someouter":
"someinner":
"someValue": 123
,
"simpleString": "string"
add a comment |
Here's how I solved the problem.
var obj =
;
var field = "someouter.someinner.someValue";
var value = 123;
function _addField( obj, field, value )
// split the field into tokens
var tokens = field.split( '.' );
// if there's more than one token, this field is an object
if( tokens.length > 1 )
var subObj = tokens[0];
// define the object
if( obj[ subObj ] !== undefined ) obj[ subObj ] = ;
// call addfield again on the embedded object
var firstDot = field.indexOf( '.' );
_addField( obj[ subObj ], field.substr( firstDot + 1 ), value );
else
// no embedded objects, just field assignment
obj[ field ] = value;
_addField( obj, field, value );
_addField(obj, 'simpleString', 'string');
console.log( JSON.stringify( obj, null, 2 ) );
Generates the following object:
"someouter":
"someinner":
"someValue": 123
,
"simpleString": "string"
Here's how I solved the problem.
var obj =
;
var field = "someouter.someinner.someValue";
var value = 123;
function _addField( obj, field, value )
// split the field into tokens
var tokens = field.split( '.' );
// if there's more than one token, this field is an object
if( tokens.length > 1 )
var subObj = tokens[0];
// define the object
if( obj[ subObj ] !== undefined ) obj[ subObj ] = ;
// call addfield again on the embedded object
var firstDot = field.indexOf( '.' );
_addField( obj[ subObj ], field.substr( firstDot + 1 ), value );
else
// no embedded objects, just field assignment
obj[ field ] = value;
_addField( obj, field, value );
_addField(obj, 'simpleString', 'string');
console.log( JSON.stringify( obj, null, 2 ) );
Generates the following object:
"someouter":
"someinner":
"someValue": 123
,
"simpleString": "string"
edited Nov 28 '16 at 16:53
answered Nov 28 '16 at 15:46
lewmalewma
1011 silver badge4 bronze badges
1011 silver badge4 bronze badges
add a comment |
add a comment |
A perfect easy way
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var newProperty = 'getThisFromUser';
data[newProperty] = 4;
console.log(data);
If you want to apply it on an array of data (ES6/TS version)
const data = [
'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 ,
'PropertyA': 11, 'PropertyB': 22, 'PropertyC': 33
];
const newProperty = 'getThisFromUser';
data.map( (d) => d[newProperty] = 4 );
console.log(data);
add a comment |
A perfect easy way
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var newProperty = 'getThisFromUser';
data[newProperty] = 4;
console.log(data);
If you want to apply it on an array of data (ES6/TS version)
const data = [
'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 ,
'PropertyA': 11, 'PropertyB': 22, 'PropertyC': 33
];
const newProperty = 'getThisFromUser';
data.map( (d) => d[newProperty] = 4 );
console.log(data);
add a comment |
A perfect easy way
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var newProperty = 'getThisFromUser';
data[newProperty] = 4;
console.log(data);
If you want to apply it on an array of data (ES6/TS version)
const data = [
'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 ,
'PropertyA': 11, 'PropertyB': 22, 'PropertyC': 33
];
const newProperty = 'getThisFromUser';
data.map( (d) => d[newProperty] = 4 );
console.log(data);
A perfect easy way
var data =
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
;
var newProperty = 'getThisFromUser';
data[newProperty] = 4;
console.log(data);
If you want to apply it on an array of data (ES6/TS version)
const data = [
'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 ,
'PropertyA': 11, 'PropertyB': 22, 'PropertyC': 33
];
const newProperty = 'getThisFromUser';
data.map( (d) => d[newProperty] = 4 );
console.log(data);
answered Feb 21 at 7:37
UmeshUmesh
2,11914 silver badges19 bronze badges
2,11914 silver badges19 bronze badges
add a comment |
add a comment |
Definitely. Think of it as a dictionary or associative array. You can add to it at any point.
19
I think we can assume an implicit "and if so, how?" in the question...
– Marc Gravell♦
Jul 26 '09 at 9:32
1
Just saying that will not help.
– Obinna Nwakwue
Aug 28 '16 at 14:51
add a comment |
Definitely. Think of it as a dictionary or associative array. You can add to it at any point.
19
I think we can assume an implicit "and if so, how?" in the question...
– Marc Gravell♦
Jul 26 '09 at 9:32
1
Just saying that will not help.
– Obinna Nwakwue
Aug 28 '16 at 14:51
add a comment |
Definitely. Think of it as a dictionary or associative array. You can add to it at any point.
Definitely. Think of it as a dictionary or associative array. You can add to it at any point.
answered Jul 26 '09 at 9:29
thedzthedz
4,4412 gold badges20 silver badges28 bronze badges
4,4412 gold badges20 silver badges28 bronze badges
19
I think we can assume an implicit "and if so, how?" in the question...
– Marc Gravell♦
Jul 26 '09 at 9:32
1
Just saying that will not help.
– Obinna Nwakwue
Aug 28 '16 at 14:51
add a comment |
19
I think we can assume an implicit "and if so, how?" in the question...
– Marc Gravell♦
Jul 26 '09 at 9:32
1
Just saying that will not help.
– Obinna Nwakwue
Aug 28 '16 at 14:51
19
19
I think we can assume an implicit "and if so, how?" in the question...
– Marc Gravell♦
Jul 26 '09 at 9:32
I think we can assume an implicit "and if so, how?" in the question...
– Marc Gravell♦
Jul 26 '09 at 9:32
1
1
Just saying that will not help.
– Obinna Nwakwue
Aug 28 '16 at 14:51
Just saying that will not help.
– Obinna Nwakwue
Aug 28 '16 at 14:51
add a comment |
protected by tchrist Sep 8 '12 at 15:05
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?