Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript, update object with dynamic keys [duplicate]

Tags:

javascript

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

like image 947
pmiranda Avatar asked Mar 20 '26 06:03

pmiranda


2 Answers

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)
like image 123
User863 Avatar answered Mar 21 '26 18:03

User863


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 );
like image 24
Devsi Odedra Avatar answered Mar 21 '26 19:03

Devsi Odedra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!