-1

I have to create a string in format like below

  "currentState[0]['children'][1]"

But I need to execute it later just like below

  currentState[0]['children'][1]

I have elements and childrens on currentState. But while looping I have to create a string. But later I need to execute as array.

I have tried almost all array methods. Array.call, bind etc. And string methods as well. Could not get the output

How can I make it

4
  • The posted question does not appear to include any attempt at all to solve the problem. StackOverflow expects you to try to solve your own problem first, as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific problem you're having in a minimal reproducible example. For more information, please see How to Ask and take the tour. Commented Sep 19, 2018 at 4:49
  • 4
    Use eval: $str = "currentState[0]['children'][1]". Then: $test = eval($str); Commented Sep 19, 2018 at 4:54
  • You can use eval function. Eval will evaluate complete string Commented Sep 19, 2018 at 4:55
  • 1
    Yes eval will get the job done, but; eval is frowned upon because it can be used for a wide variaty of attacks on your code, your application, your user, ... Commented Sep 19, 2018 at 5:10

1 Answer 1

0

Please be more specific with your question but from my understanding, you can use javascript's eval() function to execute a string as javascript, so when you need to execute it, just run eval("currentState[0]['children'][1]").

The alternative to the eval() would be

function evalFn(obj) { return Function('"use strict";return (' + obj + ')')(); }

evalFn("currentState[0]['children'][1]")

refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval for a more in-depth explanation.

Sign up to request clarification or add additional context in comments.

1 Comment

Absolutely never do this. eval is a major security risk.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.