2

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

Nick Parsons
  • 38,409
  • 6
  • 31
  • 57
pmiranda
  • 6,162
  • 9
  • 51
  • 114

2 Answers2

5

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)
User863
  • 18,185
  • 2
  • 15
  • 38
  • 1
    That's not "bracket notation". What you're using is a _[computed property name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names)_ – Andreas Dec 21 '19 at 13:23
  • Thanks, I could't learn that concept if my question were removed by duplicated. – pmiranda Dec 21 '19 at 21:18
3

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 );
Devsi Odedra
  • 5,071
  • 1
  • 21
  • 33