This works for me
function addProperty(object, property) {
// add the property to the object with a value of null
// return the object
// note: the property name is NOT 'property'. The name is the value
// object.property = property;
object[property] = null;
return object;
}
var obj = {x:1,y:null};
// undefined
obj
// {x: 1, y: null}
addProperty(obj, 'z');
// {x: 1, y: null, z: null}
Answer from Niccaman on Stack OverflowThis works for me
function addProperty(object, property) {
// add the property to the object with a value of null
// return the object
// note: the property name is NOT 'property'. The name is the value
// object.property = property;
object[property] = null;
return object;
}
var obj = {x:1,y:null};
// undefined
obj
// {x: 1, y: null}
addProperty(obj, 'z');
// {x: 1, y: null, z: null}
The preferred way of doing this if you ask me is to use Object.assign. This will copy all the properties of the second object you pass in into the first object. You can also send in multiple objects and all will be copied into the first object.
function addProperty(object, property) {
return Object.assign(object, { [property]: null });
}
How to add a property to an object that doesn't exist in its type?
Is it possible to add dynamically named properties to JavaScript object? - Stack Overflow
Can't add properties to javascript object
The shortest way to conditionally insert properties into an object literal
Videos
EDIT: I just realized I could just deep clone the object and alter that one instead.
Heres a simplified example of what I'm trying to do:
const foo = (apiReponse: {A: number, B: number) => {
return apiReponse.D = 123
}Basically I am pass in an api response and using the type thats generated from codegen (apollo graphql). However I want to add a new field to it dynamically, however its throwing an error for the obvious reason.
How do I get around this or this just one big anti pattern?
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.