I have an object with this static structure:
let obj = {
"id": "",
"id_configuration": "",
"comment": "",
"mw_assigned": "",
};
I want to update it's properties by key. For example, if I receive
const key = 'mw_assigned'
const value = '23'
Then I want to update the object and to have:
let obj = {
"id": "",
"id_configuration": "",
"comment": "",
"mw_assigned": "23",
};
How could I do? I was trying to create a new object, something like this:
const new_obj = { ...obj, key: value }
I don't know how to set the name of the key and value from the vars
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)
You can use as obj[key]
let obj = {
"id": "",
"id_configuration": "",
"comment": "",
"mw_assigned": "",
};
const key = 'mw_assigned';
const value = '23';
// obj[key] = value;
const new_obj = { ...obj, [key]: value }
console.log(new_obj );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With