JavaScript Object retrieve value dynamically - javascript

Sorry if it sounds like a stupid question
I have this following JavaScript object:
data = {
"Max" : 100
}
This same object can also have the following form:
data = {
"January": {"Max" : 100}
}
I want to use one same function to retrieve the value of Max if given the two forms
And it made me wonder if it is possible to write a conditional expressions directly in the [] when you write the values you want to retrieve? Is this following expression allowed in JavaScript? Something like this:
data[monthly ? 'month' : '']
Of course I tried it and it doesn't work. But is there another way to do such a thing in a line? monthly is a boolean

You can use the following script to do that, I have added some comments to make it clear
var data1 = {
"Max" : 100
}
var data2 = {
"January": {"Max" : 100}
}
// storing the months in an array to loop over and see if the current key is a month
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
function getMax(data) {
// if the key `Max` exists in data then just get the value of `data.Max` else loop over the months, and see if one of the months is a key and stores a truthy value, in this case it stores an object, so that's what we want and then get it's .Max value
return "Max" in data ? data.Max : data[months.filter(m => data[m] ? m : "")[0]].Max;
}
console.log(getMax(data1));
console.log(getMax(data2));

You can make use of Object.values
let data = {
"Max": 100
};
const getMax = (data) => {
//check if "Max" is available in the `data`, if so return `data.Max` else
//get values of the keys in the object using `Object.values` and
//retreive `Max` from the array
return data.Max ? data.Max : Object.values(data)[0].Max
}
console.log(getMax(data));
data = {
"January": {
"Max": 200
}
}
console.log(getMax(data));
There's yet another way of achieving this using Array.find and Optional Chaining.
let data = {
Max: 100,
};
const getMax = (data = {}) => {
return data.Max ? data.Max : Object.values(data).find(({ Max }) => Max)?.Max;
};
console.log(getMax(data));
data = {
January: { Max: 200 },
};
console.log(getMax(data));

Related

How to access a value outside of a promise [duplicate]

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 its 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?
Yes.
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
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.
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]);
ES6 introduces computed property names, which allows you to do
let a = 'key'
let myObj = {[a]: 10};
// output will be {key:10}
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
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'
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.
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
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
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"}]
It can be useful if mixed new property add in runtime:
data = { ...data, newPropery: value}
However, spread operator use shallow copy but here we assign data to itself so should lose nothing
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!
I was looking for a solution where I can use dynamic key-names inside the object declaration (without using ES6 features like ... or [key]: value)
Here's what I came up with:
var obj = (obj = {}, obj[field] = 123, obj)
It looks a little bit complex at first, but it's really simple. We use the Comma Operator to run three commands in a row:
obj = {}: creates a new object and assigns it to the variable obj
obj[field] = 123: adds a computed property name to obj
obj: use the obj variable as the result of the parentheses/comma list
This syntax can be used inside a function parameter without the requirement to explictely declare the obj variable:
// The test function to see the result.
function showObject(obj) {
console.log(obj);
}
// My dynamic field name.
var field = "myDynamicField";
// Call the function with our dynamic object.
showObject( (obj = {}, obj[field] = 123, obj) );
/*
Output:
{
"myDynamicField": true
}
*/
Some variations
"strict mode" workaround:
The above code does not work in strict mode because the variable "obj" is not declared.
// This gives the same result, but declares the global variable `this.obj`!
showObject( (this.obj = {}, obj[field] = 123, obj) );
ES2015 code using computed property names in initializer:
// Works in most browsers, same result as the other functions.
showObject( {[field] = 123} );
This solution works in all modern browsers (but not in IE, if I need to mention that)
Super hacky way using JSON.parse():
// Create a JSON string that is parsed instantly. Not recommended in most cases.
showObject( JSON.parse( '{"' + field +'":123}') );
// read: showObject( JSON.parse( '{"myDynamicfield":123}') );
Allows special characters in keys
Note that you can also use spaces and other special characters inside computed property names (and also in JSON.parse).
var field = 'my dynamic field :)';
showObject( {[field] = 123} );
// result: { "my dynamic field :)": 123 }
Those fields cannot be accessed using a dot (obj.my dynamic field :) is obviously syntactically invalid), but only via the bracket-notation, i.e., obj['my dynamic field :)'] returns 123
The simplest and most portable way is.
var varFieldName = "good";
var ob = {};
Object.defineProperty(ob, varFieldName , { value: "Fresh Value" });
Based on #abeing answer!
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.
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" || typeof(o)==="undefined" || o===null)
return undefined;
var v=varname.split(".");
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
if(typeof(o[v[v.length-1]])==="undefined")
return undefined;
else
return o[v[v.length-1]];
}
function AssignValue(varname,value,o=window)
{
if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
return;
var v=varname.split(".");
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
o[v[v.length-1]]=value;
}
Example:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
This is the same that o.object.subobject.property
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"
}
Yes it is possible. I have achieved using below implementation. for that I am getting array in response which I want in an object as list of attributes.
response = {
"equityMonths": [
{
"id": 1,
"month": "JANUARY",
"isEligible": false
},
{
"id": 2,
"month": "FEBRUARY",
"isEligible": true
},
{
"id": 3,
"month": "MARCH",
"isEligible": false
},
{
"id": 4,
"month": "APRIL",
"isEligible": true
},
{
"id": 5,
"month": "MAY",
"isEligible": false
},
{
"id": 6,
"month": "JUNE",
"isEligible": true
},
{
"id": 7,
"month": "JULY",
"isEligible": true
},
{
"id": 8,
"month": "AUGUST",
"isEligible": false
},
{
"id": 9,
"month": "SEPTEMBER",
"isEligible": true
},
{
"id": 10,
"month": "OCTOBER",
"isEligible": false
},
{
"id": 11,
"month": "NOVEMBER",
"isEligible": true
},
{
"id": 12,
"month": "DECEMBER",
"isEligible": false
}
]
}
here, I want equityMonths as an object and Jan to Dec it's key and isEligible as value. for that we have to use Object class's defineProperty() method which allows to add dynamic property into objects.
code for adding property dynamically to the object.
let equityMonth = new Object();
response.equityMonths.forEach(element => {
Object.defineProperty(equityMonth, element['month'], {
value: element['isEligible'],
writable: true,
enumerable: true,
configurable: true
});
});
console.log("DATA : " + JSON.stringify(equityMonth));
in above code we have array of equityMonths which we have converted as property into the object.
output:
DATA : {"JANUARY":false,"FEBRUARY":true,"MARCH":false,"APRIL":true,"MAY":false,"JUNE":true,"JULY":true,"AUGUST":false,"SEPTEMBER":true,"OCTOBER":false,"NOVEMBER":true,"DECEMBER":false}
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);
Definitely. Think of it as a dictionary or associative array. You can add to it at any point.

why does ```map``` work on array but ```find``` breaks the code

I am working in React Native with a variable that has a value equal to an array of objects:
const list2020 = [
{
"monthId": "4",
"monthName": "May",
"firstEkadasi": {
"jsDayOfWeek": "1",
"dayOfWeek": "Monday",
"dayInMonth": "4",
"ekadasiName": "Mohini"
},
"secondEkadasi": {
"jsDayOfWeek": "1",
"dayOfWeek": "Monday",
"dayInMonth": "18",
"ekadasiName": "Apara"
},
"thirdEkadasi": {}
},
{
"monthId": "5",
"monthName": "June",
"firstEkadasi": {
"jsDayOfWeek": "2",
"dayOfWeek": "Tuesday",
"dayInMonth": "2",
"ekadasiName": "Pandava Nirjala"
},
"secondEkadasi": {
"jsDayOfWeek": "3",
"dayOfWeek": "Wednesday",
"dayInMonth": "17",
"ekadasiName": "Yogini"
},
"thirdEkadasi": {}
}
]
I have a function that maps over this array:
function TestingMyCode() {
const getCurrentMonth = new Date().getMonth();
let plusOne = getCurrentMonth + 1
let currentMonthIndex = list2020.findIndex((list2020) => list2020.monthId == getCurrentMonth);
let nextMonthIndex = currentMonthIndex + 1;
return (
list2020.find((list, index, array) => {
if (list.thirdEkadasi.dayOfWeek == undefined) {
return (
<View key={index}>
<Text style={styles.displayEkadasi}>{return-values-of-next-object-in-array (I want to return the values of the next month)}</Text>
</View>
)
}
})
)
}
When I use list2020.map I can get a result (even though it is not the desired result).
However, when I used list2020.find it breaks the app with an error
Objects are not valid as a React Child (found: object with keys {monthID, monthName,...}). If you meant to render a collection of children, use an array instead
Is there a vanilla JavaScript way of fixing this?
My objective is to display the values from the next object in the array (if the current object in array does not meet criteria:
If the current Month and date (which is May 19) is greater than the dates in the object
show the values from the next month (June)
Since the date is after May 18th, my app is not showing any text. I could easily display text with if(data.monthId == month && data.firstEkadasi.dayInMonth >= dayOfMonth) {<Text>display text</Text>}
But I am stuck if the dayInMonth is less than current date. For example, it's May 19 and the object at index 0 has two Ekadasi dates; but both dates are less than 19.
How can I display the values from the next objects in the array?
You can view repo of my code here
The syntax of Array.prototype.find is arr.find(callback(element[, index[, array]])[, thisArg]) and the callback function should return Boolean(true/false).
The find() method returns the value of the first element in the provided array that satisfies the provided testing function.
You should use the filter() method instead of find() to display all values that meet the criteria.
so you should use
return (
list2020.filter((list) => list.thirdEkadasi.dayOfWeek == undefined)
.map((item) =>
<View key={index}>
<Text style={styles.displayEkadasi}>{return-values-of-next-object-in-array (I want to return the values of the next month)}</Text>
</View>);
);
So what you want to do will be like this:
const newList2020 = list2020.map((item) => ({
monthId: item.monthId,
monthName: item.monthName,
ekadasi: [
item.firstEkadasi,
item.secondEkadasi,
item.thirdEkadasi
]
});
const thisMonth = new Date().getMonth();
const todayDate = new Date().getDate();
newList2020.filter(item => (
item.ekadasi.find(ekadasi =>
item.monthId > thisMonth
|| (item.monthId === thisMonth && ekadasi.dayInMonth >= todayDate)
) !== undefined
)).map((item, index) =>
<View key={index}>
<Text style={styles.displayEkadasi}>{return-values-of-next-object-in-array (I want to return the values of the next month)}</Text>
</View>
);
The problem here is FIND expects a callback function, not just an item. In a way, it's very much like FILTER.
The following example is from MDN docs
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
const result = inventory.find( ({ name }) => name === 'cherries' );
console.log(result) // { name: 'cherries', quantity: 5 }
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
So you need to rewrite your => line.

How to replace after . part with my string? [duplicate]

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 its 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?
Yes.
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
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.
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]);
ES6 introduces computed property names, which allows you to do
let a = 'key'
let myObj = {[a]: 10};
// output will be {key:10}
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
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'
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.
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
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
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"}]
It can be useful if mixed new property add in runtime:
data = { ...data, newPropery: value}
However, spread operator use shallow copy but here we assign data to itself so should lose nothing
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!
I was looking for a solution where I can use dynamic key-names inside the object declaration (without using ES6 features like ... or [key]: value)
Here's what I came up with:
var obj = (obj = {}, obj[field] = 123, obj)
It looks a little bit complex at first, but it's really simple. We use the Comma Operator to run three commands in a row:
obj = {}: creates a new object and assigns it to the variable obj
obj[field] = 123: adds a computed property name to obj
obj: use the obj variable as the result of the parentheses/comma list
This syntax can be used inside a function parameter without the requirement to explictely declare the obj variable:
// The test function to see the result.
function showObject(obj) {
console.log(obj);
}
// My dynamic field name.
var field = "myDynamicField";
// Call the function with our dynamic object.
showObject( (obj = {}, obj[field] = 123, obj) );
/*
Output:
{
"myDynamicField": true
}
*/
Some variations
"strict mode" workaround:
The above code does not work in strict mode because the variable "obj" is not declared.
// This gives the same result, but declares the global variable `this.obj`!
showObject( (this.obj = {}, obj[field] = 123, obj) );
ES2015 code using computed property names in initializer:
// Works in most browsers, same result as the other functions.
showObject( {[field] = 123} );
This solution works in all modern browsers (but not in IE, if I need to mention that)
Super hacky way using JSON.parse():
// Create a JSON string that is parsed instantly. Not recommended in most cases.
showObject( JSON.parse( '{"' + field +'":123}') );
// read: showObject( JSON.parse( '{"myDynamicfield":123}') );
Allows special characters in keys
Note that you can also use spaces and other special characters inside computed property names (and also in JSON.parse).
var field = 'my dynamic field :)';
showObject( {[field] = 123} );
// result: { "my dynamic field :)": 123 }
Those fields cannot be accessed using a dot (obj.my dynamic field :) is obviously syntactically invalid), but only via the bracket-notation, i.e., obj['my dynamic field :)'] returns 123
The simplest and most portable way is.
var varFieldName = "good";
var ob = {};
Object.defineProperty(ob, varFieldName , { value: "Fresh Value" });
Based on #abeing answer!
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.
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" || typeof(o)==="undefined" || o===null)
return undefined;
var v=varname.split(".");
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
if(typeof(o[v[v.length-1]])==="undefined")
return undefined;
else
return o[v[v.length-1]];
}
function AssignValue(varname,value,o=window)
{
if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
return;
var v=varname.split(".");
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
o[v[v.length-1]]=value;
}
Example:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
This is the same that o.object.subobject.property
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"
}
Yes it is possible. I have achieved using below implementation. for that I am getting array in response which I want in an object as list of attributes.
response = {
"equityMonths": [
{
"id": 1,
"month": "JANUARY",
"isEligible": false
},
{
"id": 2,
"month": "FEBRUARY",
"isEligible": true
},
{
"id": 3,
"month": "MARCH",
"isEligible": false
},
{
"id": 4,
"month": "APRIL",
"isEligible": true
},
{
"id": 5,
"month": "MAY",
"isEligible": false
},
{
"id": 6,
"month": "JUNE",
"isEligible": true
},
{
"id": 7,
"month": "JULY",
"isEligible": true
},
{
"id": 8,
"month": "AUGUST",
"isEligible": false
},
{
"id": 9,
"month": "SEPTEMBER",
"isEligible": true
},
{
"id": 10,
"month": "OCTOBER",
"isEligible": false
},
{
"id": 11,
"month": "NOVEMBER",
"isEligible": true
},
{
"id": 12,
"month": "DECEMBER",
"isEligible": false
}
]
}
here, I want equityMonths as an object and Jan to Dec it's key and isEligible as value. for that we have to use Object class's defineProperty() method which allows to add dynamic property into objects.
code for adding property dynamically to the object.
let equityMonth = new Object();
response.equityMonths.forEach(element => {
Object.defineProperty(equityMonth, element['month'], {
value: element['isEligible'],
writable: true,
enumerable: true,
configurable: true
});
});
console.log("DATA : " + JSON.stringify(equityMonth));
in above code we have array of equityMonths which we have converted as property into the object.
output:
DATA : {"JANUARY":false,"FEBRUARY":true,"MARCH":false,"APRIL":true,"MAY":false,"JUNE":true,"JULY":true,"AUGUST":false,"SEPTEMBER":true,"OCTOBER":false,"NOVEMBER":true,"DECEMBER":false}
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);
Definitely. Think of it as a dictionary or associative array. You can add to it at any point.

How to create a query in Mongoose/Mongodb to obtain this json?

I'm trying to obtain an object like this from my mongodb, counting the OS per month:
{January: {Android: 30, iOS: 10, winPhone: 5}, February: {Android: 4, iOS: 40}, etc}.
And here is my mongoose schema:
var MySchema = new Schema({
date: {type: Date, default: Date.now},
os: String
});
Can give me someone an idea? Is there a way to create a single query to return me the entire object or should I build it piece by piece, unifying multiple queries?
Thank you!
You're probably better off using an output structure that's more natural for MongoDB where the keys are static and the values contain the data. Then you can use an aggregation pipeline to do this as:
MyModel.aggregate([
// Group the docs by month & os
{$group: {_id: {month: {$month: '$date'}, os: '$os'}, count: {$sum: 1}}},
// Group again by just month
{$group: {_id: '$_id.month', counts: {$push: {os: '$_id.os', count: '$count'}}}},
// Rename _id to month
{$project: {month: '$_id', counts: 1, _id: 0}}
], callback);
Which generates output like:
{
"result" : [
{
"counts" : [
{
"os" : "winPhone",
"count" : 2
},
{
"os" : "iOS",
"count" : 1
},
{
"os" : "Android",
"count" : 2
}
],
"month" : 1
},
{
"counts" : [
{
"os" : "iOS",
"count" : 2
},
{
"os" : "Android",
"count" : 1
}
],
"month" : 2
}
],
"ok" : 1
}
If you really want the original format you can then post-process the result to reshape it however you want.
Since you want to project values as keys in the output, you can't achieve this using the aggregation pipeline. None of the pipeline operators accept values as keys. You need to write map reduce functions. The map function that groups the records based on the year. So the year is emitted as the key. The value being each os name and 'month' in which it was sold.
The map function:
var map = function(){
emit(this.date.getFullYear(),
{"month":this.date.getMonth(),"os":this.os});
}
The reduce function for each group now aggregates the count of different types of os sold in a month for that year.
var reduce = function(id,osArr){
var result = {};
var osCount = {};
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
for(var i=0;i<osArr.length;i++)
{
var mon = monthNames[(osArr[i].month)-1];
if(!osCount.hasOwnProperty(mon))
{
osCount[mon] = {};
}
if(osCount[mon].hasOwnProperty(osArr[i].os))
{
osCount[mon][osArr[i].os]++;
}
else
{
osCount[mon][osArr[i].os] = 1;
}
}
result[id] = osCount;
return result;
}
Call the map reduce function on the collection and dump it to a new collection named 'temp'.
var o = {};
o.map = map;
o.reduce = reduce;
o.out = { replace: 'temp' }
o.verbose = true;
ModelName.mapReduce(o, function (err, results) {
console.log(results)
})
This yields the following Sample results:
> db.temp.find({},{"value":1,"_id":0})
{ "value" : { "2013" : { "November" : { "Android" : 2, "ios" : 2, "blackberry" :
1 } } } }
{ "value" : { "2014" : { "October" : { "Android" : 3, "ios" : 2 } } } }

Cannot Access Window Variable [duplicate]

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 its 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?
Yes.
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
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.
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]);
ES6 introduces computed property names, which allows you to do
let a = 'key'
let myObj = {[a]: 10};
// output will be {key:10}
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
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'
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.
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
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
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"}]
It can be useful if mixed new property add in runtime:
data = { ...data, newPropery: value}
However, spread operator use shallow copy but here we assign data to itself so should lose nothing
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!
I was looking for a solution where I can use dynamic key-names inside the object declaration (without using ES6 features like ... or [key]: value)
Here's what I came up with:
var obj = (obj = {}, obj[field] = 123, obj)
It looks a little bit complex at first, but it's really simple. We use the Comma Operator to run three commands in a row:
obj = {}: creates a new object and assigns it to the variable obj
obj[field] = 123: adds a computed property name to obj
obj: use the obj variable as the result of the parentheses/comma list
This syntax can be used inside a function parameter without the requirement to explictely declare the obj variable:
// The test function to see the result.
function showObject(obj) {
console.log(obj);
}
// My dynamic field name.
var field = "myDynamicField";
// Call the function with our dynamic object.
showObject( (obj = {}, obj[field] = 123, obj) );
/*
Output:
{
"myDynamicField": true
}
*/
Some variations
"strict mode" workaround:
The above code does not work in strict mode because the variable "obj" is not declared.
// This gives the same result, but declares the global variable `this.obj`!
showObject( (this.obj = {}, obj[field] = 123, obj) );
ES2015 code using computed property names in initializer:
// Works in most browsers, same result as the other functions.
showObject( {[field] = 123} );
This solution works in all modern browsers (but not in IE, if I need to mention that)
Super hacky way using JSON.parse():
// Create a JSON string that is parsed instantly. Not recommended in most cases.
showObject( JSON.parse( '{"' + field +'":123}') );
// read: showObject( JSON.parse( '{"myDynamicfield":123}') );
Allows special characters in keys
Note that you can also use spaces and other special characters inside computed property names (and also in JSON.parse).
var field = 'my dynamic field :)';
showObject( {[field] = 123} );
// result: { "my dynamic field :)": 123 }
Those fields cannot be accessed using a dot (obj.my dynamic field :) is obviously syntactically invalid), but only via the bracket-notation, i.e., obj['my dynamic field :)'] returns 123
The simplest and most portable way is.
var varFieldName = "good";
var ob = {};
Object.defineProperty(ob, varFieldName , { value: "Fresh Value" });
Based on #abeing answer!
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.
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" || typeof(o)==="undefined" || o===null)
return undefined;
var v=varname.split(".");
if(!v.length)
return undefined;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
if(typeof(o[v[v.length-1]])==="undefined")
return undefined;
else
return o[v[v.length-1]];
}
function AssignValue(varname,value,o=window)
{
if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
return;
var v=varname.split(".");
if(!v.length)
return;
for(var i=0;i<v.length-1;i++)
{
if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
o[v[i]]={};
o=o[v[i]];
}
o[v[v.length-1]]=value;
}
Example:
ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
This is the same that o.object.subobject.property
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"
}
Yes it is possible. I have achieved using below implementation. for that I am getting array in response which I want in an object as list of attributes.
response = {
"equityMonths": [
{
"id": 1,
"month": "JANUARY",
"isEligible": false
},
{
"id": 2,
"month": "FEBRUARY",
"isEligible": true
},
{
"id": 3,
"month": "MARCH",
"isEligible": false
},
{
"id": 4,
"month": "APRIL",
"isEligible": true
},
{
"id": 5,
"month": "MAY",
"isEligible": false
},
{
"id": 6,
"month": "JUNE",
"isEligible": true
},
{
"id": 7,
"month": "JULY",
"isEligible": true
},
{
"id": 8,
"month": "AUGUST",
"isEligible": false
},
{
"id": 9,
"month": "SEPTEMBER",
"isEligible": true
},
{
"id": 10,
"month": "OCTOBER",
"isEligible": false
},
{
"id": 11,
"month": "NOVEMBER",
"isEligible": true
},
{
"id": 12,
"month": "DECEMBER",
"isEligible": false
}
]
}
here, I want equityMonths as an object and Jan to Dec it's key and isEligible as value. for that we have to use Object class's defineProperty() method which allows to add dynamic property into objects.
code for adding property dynamically to the object.
let equityMonth = new Object();
response.equityMonths.forEach(element => {
Object.defineProperty(equityMonth, element['month'], {
value: element['isEligible'],
writable: true,
enumerable: true,
configurable: true
});
});
console.log("DATA : " + JSON.stringify(equityMonth));
in above code we have array of equityMonths which we have converted as property into the object.
output:
DATA : {"JANUARY":false,"FEBRUARY":true,"MARCH":false,"APRIL":true,"MAY":false,"JUNE":true,"JULY":true,"AUGUST":false,"SEPTEMBER":true,"OCTOBER":false,"NOVEMBER":true,"DECEMBER":false}
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);
Definitely. Think of it as a dictionary or associative array. You can add to it at any point.

Categories