How to set a Javascript object values dynamically?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
Is it possible to add dynamically named properties to JavaScript object?
Yes.
var data = { 'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3};
data["PropertyD"] = 4;
// dialog box with 4 in italert(data.PropertyD);alert(data["PropertyD"]);
JavaScript, update object with dynamic keys
Use Computed property names
This is reminiscent of the bracket notation of the property accessor
syntax
let obj = { "id": "", "id_configuration": "", "comment": "", "mw_assigned": "",};
const key = 'mw_assigned'const value = '23'
const new_obj = { ...obj, [key]: value }
console.log(new_obj)
Accessing an object property with a dynamically-computed name
There are two ways to access properties of an object:
- Dot notation:
something.bar
- Bracket notation:
something['bar']
The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:
var something = {
bar: 'foo'
};
var foo = 'bar';
// both x = something[foo] and something[foo] = x work as expected
console.log(something[foo]);
console.log(something.bar)
How to Set Dynamic Properties to Variable in TypeScript?
I think this will do what you want:
let x : {[key: string]: any} = {};
You will have to set x to an empty object otherwise you would be trying to access properties of undefined
Dynamically set javascript object key-values using variable chaining
You can use regex to extract key name and then using array#reduce
iterate through each key and create object and for the last key assign your value.
const test = {},
value = '18 test st',
path = `['details']['address']['line1']`;
path.match(/\w+/g).reduce((o, key, i, a) => {
o[key] ||= {};
if(i === a.length - 1) {
o[key] = value;
}
return o[key];
}, test);
console.log(test);
dynamically set object value with undefined key
You can't access a nested property that doesn't exist, even if you alternate it with || 0
on the right-hand side:
const obj = {};
// Forbidden:
console.log(obj.foo.bar);
Related Topics
JavaScript Module Pattern with Example
Merge Keys Array and Values Array into an Object in JavaScript
How to Prevent Closing Browser Window
Youtube Iframe Player API - Onstatechange Not Firing
Safari Web Extension - Injecting Script Only When Extension Button Is Clicked
How to Include Newlines in Labels in D3 Charts
Angular 2: Two Backend Service Calls on Success of First Service
How to Detect When a Youtube Video Finishes Playing
Vue.Js - How to Properly Watch for Nested Data
Can a Site Invoke a Browser Extension
Rails Specify Load Order of JavaScript Files
How Can D3.Transform Be Used in D3 V4
Creating a "Sticky" Fixed-Position Item That Works on iOS Safari