0

I want to convert string to expression but the issue is I'm accessing an array and the index is a string that should be numeric.

E.g.: path = 'this.categoriesData[1].children[0]'

Error: Uncaught TypeError: Cannot read properties of undefined (reading '1')

The error is from eval(path).

Can anyone help me with this?

Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
Sanjay Lohar
  • 520
  • 2
  • 8
  • Could you give a bit more context about it? What is `this`, `categoriesData` and `children`? What is their datatype? – J. Meier Jun 07 '22 at 06:36
  • categoriesData is array and children is also an array in the object of categoriesData – Sanjay Lohar Jun 07 '22 at 06:38
  • 2
    As per the error, `this.categoriesData` is not defined. Can you please check if you are able to access this.categoriesData or not – Debug Diva Jun 07 '22 at 06:38
  • I'd recommend [Accessing nested JavaScript objects and arrays by string path](https://stackoverflow.com/q/6491463) instead of trying to access a completely arbitrary string as path. – VLAZ Jun 07 '22 at 06:39
  • Could you share the surrounding code? Seems like you are in a wrong scope. – J. Meier Jun 07 '22 at 06:39
  • The issue is that `this.categoriesData` is either empty, only has a single item or holds `undefined` in its second item. That's what the error tells you. So in order to solve the error, we need to know how you "create" this data. – Philipp Meissner Jun 07 '22 at 06:54
  • 1
    @PhilippMeissner that's wrong. From the error message it's clear that `this.categoriesData` is undefined. – derpirscher Jun 07 '22 at 07:02
  • @derpirscher You're right. The argumentation still holds true though :p – Philipp Meissner Jun 07 '22 at 07:03
  • Besides mentioning the obvious *eval is quite dangerous thing and should be handled with extreme care*, what is the result of `eval(this)`? I suspect, the eval doesn't have the correct context – derpirscher Jun 07 '22 at 07:05
  • @PhilipMeissner actually the argumentation doesn't hold, because it leads to to check the contents of a (non existing) array, whereas the (most probable) cause of this error is a wrong `this` context in the eval. Ie at the point where eval is called `this.categoriesData` may be perfectly fine. But in the context of eval's execution, `this` may be something entirely different – derpirscher Jun 07 '22 at 07:08
  • It's not undefined. The problem is 1 is string and it should be a number to access the object from this.categoriesData – Sanjay Lohar Jun 07 '22 at 07:38
  • @SanjayLohar yes, the error clearly states, that `this.categoriesData` is undefined. That the property `'1'` is enclosed into quotes is just for clarification. It's obviously not a string in `this.categoriesData[1]...` – derpirscher Jun 07 '22 at 20:29

0 Answers0