0

I have an object that has numbers as the keys.

item:{
   1:'test 1'
   2:'test 2'
   3:'test 3'
}

The object is generated automatically so the keys are not always the same. So in my method, I pass in the key as a string (ex:'1') and the changed value like so:

function changeValues(key,value){
   this.item[key] = value
}

For some reason, this doesn't change my data but instead if I do this, it works perfectly fine.

function changeValues(key,value){
   this.item['1'] = value
}

Is there a reason for this behavior and is there anyway to fix it so I can use dynamic property names?

  • how does `this.item` looks like – bill.gates Jun 02 '20 at 18:22
  • `this.item` looks like the item object in the 1st code block. @Ifaruki – Sean Debenport Jun 02 '20 at 18:31
  • Can you put this component in a codepen or something similar? I'm unable to recreate the problem. – Jacob Jun 02 '20 at 18:35
  • i am also unable to recreate the problem, it works fine for me – bill.gates Jun 02 '20 at 18:36
  • my guess is you dont pass the right, or any parameters to the function, maybe you also open your console with F12, maybe you have an error that stops your vue app – bill.gates Jun 02 '20 at 18:36
  • I didn't specify, but is it because that deep object? In data I have an array called items with multiple item objects. – Sean Debenport Jun 02 '20 at 18:55
  • Ok I think I found the issue. Key is equal to different integers but whenever I convert it tostring using `string(key)` so I can use it as a key, it doesn't do it correctly. I check the typecast of key to make sure its a string and it does say its a string in the console. – Sean Debenport Jun 02 '20 at 19:00

1 Answers1

0

You cannot use an integer value as a key in an object. It will be converted to a string value. See this answer to a similar question.

As for accessing a value by a constant string key or by a key from a variable there si no difference. Try this code:

var a = { 1: 'test1', 2: 'test2' }
var b = '1'
console.log(a['1']  === a[b])
Anatoly
  • 20,799
  • 3
  • 28
  • 42