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
  • 45,728
  • 6
  • 46
  • 64
pmiranda
  • 7,602
  • 14
  • 72
  • 155

2 Answers2

6

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
  • 19,346
  • 2
  • 17
  • 41
  • 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
4

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,244
  • 1
  • 23
  • 37