20

I would like to know if there is a clean way to set the value of a key from a string variable when using spread syntax in es6?

Something like the following:

let keyVar = 'newKey'
let newObject = {keyVar:{some:'json'},...oldObject}


But this leads to:

{"keyVar":{"some":"json"}, ... }

rather than:

{"newKey":{"some":"json"}, ... }

1
  • 1
    FYI, "spread properties" are not part of ES6. They are currently a proposal, i.e. an experimental feature. But it doesn't change how to set the property anyway. It also has nothing to do with JSON. Commented Dec 22, 2016 at 22:58

1 Answer 1

62

You can use computed properties:

const keyVar = 'newKey';
const newObject = { [keyVar]: { some: 'json' } };
console.log(newObject);

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.