简体   繁体   中英

Destructuring object when setting property name and key dynamically

I'm having a hard time sorting out how make the linter happy by destructuring when dynamically setting an object property and key.

How would I destructure this?

const myobj = { foo: 'bar' };
const key = 'foo';
const val = 'baz';

// This is the problem line
myobj[key] = val;

:: I cannot delete and repost so I'm appending to the question here ::

All I want to do is this: myobj.foo = 'baz' but foo is also a variable.

The linter setup on this project tells me to destructure when I try myobj[key] = val;

The bit of code you posted is not really relevant to destructuring .

 const myobj = { foo: 'bar' }; const key = 'foo'; const val = 'bar 2'; // This is the problem line myobj[key] = val; console.log(myobj);

Destructuring would be more like this:

 const myobj = { foo: 'bar' }; const {foo} = myobj; console.log(foo);

const myobj[key] = val;
           ^^^^^

You are trying to declare a property, which is not possible.

A simple assingment without const should work.

myobj[key] = val;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM