Using spread operator to update an object value

前端 未结 2 1732
别那么骄傲
别那么骄傲 2020-12-08 02:18

I have a function which adds a key to incoming object, but I have been told to use spread operator for that, I have been told that I can use the spread operator to create a

2条回答
  •  Happy的楠姐
    2020-12-08 03:07

    If you know the name of the property (a in the example below), then @crowder's answer is perfect:

    const o3 = {...o1, a: "updated a"};
    console.log(o3);
    

    If the property name is in a variable, then you need to use Computed Property names syntax:

    let variable = 'foo'
    const o4 = {...o1, [variable]: "updated foo"};
    console.log(o4);
    

提交回复
热议问题