-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

Volker E.
  • 5,911
  • 11
  • 47
  • 64
raj m
  • 1,863
  • 6
  • 21
  • 37
  • The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), 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 [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Sep 19 '18 at 04:49
  • 4
    Use eval: `$str = "currentState[0]['children'][1]"`. Then: $test = eval($str); – protoproto Sep 19 '18 at 04:54
  • You can use eval function. Eval will evaluate complete string – Sourabh Somani Sep 19 '18 at 04: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, ... – Thomas Sep 19 '18 at 05:10

1 Answers1

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.