-1

I've got basic variable that I'm getting from my api:

nurseListSpeciality.avatar = "srcs[14]"

I want to change srcs[14] into array name, that my object should be like:

nurseListSpeciality:[{avatar: srcs[14]}]

The main problem is that I don't want to execute the reference on the array, but I want to put just a name of it inside my object.

This is why I failed to use eval(). Eval is trying to get srcs[14] value and put it into my object. This is not what I want.

gileneusz
  • 1,435
  • 8
  • 30
  • 51

2 Answers2

0

If you're open to use lodash, using _.get is a good way to do this:

nurseListSpeciality.avatar = _.get(window, "srcs[14]");

This code assumes that srcs is a variable which is available globally (in window object). If you have some other scope, you should replace window with the appropriate object.

31piy
  • 23,323
  • 6
  • 47
  • 67
0

vuejs console gives:

Uncaught (in promise) TypeError: this.nurseListSpeciality[i].eval is not a function

Error message tells you that this.nurseListSpeciality[i] doesn't have an eval method, you need to invoke global eval on this.nurseListSpeciality[i].avatar as.

 eval(this.nurseListSpeciality[i].avatar)

Note

  • This will not work if you don't have a variable srcs available in your current scope.
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • this will not work because eval will take srcs value from the scope and execute it instead of creating srcs[14] variable from string as it is – gileneusz Apr 13 '18 at 08:39
  • `eval` doesn't create variables unless there is a code to create variables like `eval( "var src=[]; src[14]" )`. If you can state your actual requirement, I can suggest a possible solution. – gurvinder372 Apr 13 '18 at 08:40
  • hm, let me try this – gileneusz Apr 13 '18 at 08:42
  • Even in this case it `src[14]` will return `undefined` since array size is 0. Looks like you have a control over what you can pass as value. If you can share the actual requirement, I can suggest a better solution. – gurvinder372 Apr 13 '18 at 08:43
  • when i declare `let srcs = "random text"` into my method, I've got `undefined` – gileneusz Apr 13 '18 at 08:46
  • because `srcs[14]` will still be `undefined`, make the string of length more than 14 characters. – gurvinder372 Apr 13 '18 at 08:47
  • but I don't want to get `srcs[*]` value inside my object, I want to get variable name: `srcs[*]` - this is the case – gileneusz Apr 13 '18 at 08:48