0

I have this array of object

const d = [{
  a_1: 1,
  b_2: 2
}]

How can I update a_1 value to 2 without creating a temporary variable?

const myKey = 'a_1'
const myValue = 2
d.map(obj => ({...obj, obj[myKey]:myValue})) //why this won't work?
user3106579
  • 643
  • 1
  • 6
  • 15
  • I take it `myKey` is dynamic? If so, of course, [Snow's answer](https://stackoverflow.com/a/58155137/157247) is correct, and this is covered by the answers to [this question](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name). If it's *not* dynamic, just specify the property directly: `const result = d.map(obj => ({...obj, a_1: 2}));` – T.J. Crowder Sep 29 '19 at 12:22
  • @T.J.Crowder a_1, will be populated to other object, how to avoid that? – user3106579 Sep 29 '19 at 12:24
  • I'm afraid I don't know what you mean by that...? – T.J. Crowder Sep 29 '19 at 12:36
  • @T.J.Crowder I'm stuck using the logic to update the form's state https://codesandbox.io/s/cocky-ives-cx5nx – user3106579 Sep 29 '19 at 13:13

1 Answers1

0

Remove the obj from obj[myKey] so that [myKey] is correctly seen as a computed property name.

const transformedDs = d.map(obj => ({...obj, [myKey]:myValue})) 
Snow
  • 3,820
  • 3
  • 13
  • 39