0

Why myObj not recognized from new object.

I just want my object get myValue as key how can I implement it?

my object

let myObj = {
  0: 'adi',
  1: 'itzik'
}

const myValue=4;
myObj = { ...myObj, ...{ myValue: 'dani' } };

after code above

my object

let myObj = {
  0: 'adi',
  1: 'itzik',
  myValue: 'dani' // should be 4:4
}
Red
  • 6,599
  • 9
  • 43
  • 85
Lichay Tiram
  • 283
  • 3
  • 12
  • 3
    `{ myValue: 'dani' }` creates an object with a key of `"myValue"`. If you want to use the *contents* of `myValue` as the key it'd be `{ [myValue]: 'dani' }`. – Dave Newton May 18 '21 at 17:48

1 Answers1

2

Use a computed property name.

let myObj = {
  0: 'adi',
  1: 'itzik'
}
const myValue = 4;
myObj = { ...myObj, ...{[myValue]: myValue}};
console.log(myObj)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    There are already [many](https://stackoverflow.com/a/36024066/6243352) [dupes](https://stackoverflow.com/a/19837961/6243352) for this. Why not suggest one to avoid reinventing whole threads of knowledge? – ggorlen May 18 '21 at 17:55
  • Thanks it work, but why we need it ? [] – Lichay Tiram May 18 '21 at 18:01
  • 1
    @LichayTiram Using square brackets will set the property name as the value of the expression instead of the literal name `'myValue'`. See [this](https://eloquentcode.com/computed-property-names-in-javascript). – Unmitigated May 18 '21 at 19:13