1

I am trying to access JSON with variables at forEach by using the eval function. But something is missing. Do I really need to pass JSON into forEach function?

var z = {
  "ID1": {
    "TF": {
      "15M": {
        "A2": "GOLDEN",
        "timestamp": "October 8, 2018 4:36 PM"
      }
    }
  }
}

var signal = JSON.stringify(z, null, 4);
var TF = ["15M", "1H", "4H"];
var message = ["A1", "A2", "A3", "A4"];
var symbols = ["ID1", "ID2", "ID3"];
symbols.forEach(function(s) {
  if (eval('signal.' + s) != undefined) {
    TF.forEach(function(e) {
      if (eval('signal.' + s + '.TF["' + e + '"]') != undefined) {
        message.forEach(function(i) {
          if (eval('signal.' + s + '.TF["' + e + '"].' + i) != undefined) {
            $('#' + s + e + i).text(eval('signal.' + s + '.TF["' + e + '"].' + i));
            console.log(eval('signal.' + s + '.TF["' + e + '"].' + i));
          }
        });
      }
    });
  }
});
Ivar
  • 6,138
  • 12
  • 49
  • 61
Keyme
  • 49
  • 1
  • 5
  • 2
    Please try and get rid of eval.. For ex: You can change this `eval('signal.' +s )` to `signal[s]`. – Selvakumar Arumugam Oct 08 '18 at 18:42
  • 1
    What's the something that's missing? What problem are you having? Why are you using eval here at all? For more advice on how to write a good question, see: https://stackoverflow.com/help/how-to-ask – Geoffrey Wiseman Oct 08 '18 at 18:46
  • 1
    var signal = JSON.stringify(z, null, 4); -> it convert JSON to string. So when you eval('signal.' + s), it is undefined. And please do not use eval – Duong Dang Oct 08 '18 at 18:46
  • 1
    You've posted what's known as an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Instead of asking us for help with your end-goal, you've asked for help with a solution. It's like asking *"How do I put a nail into a wall with a spoon"*, when really you should be asking *"How do I hang a picture?"*. Take a step back and let us know what you're trying to accomplish. And to echo what others have said, there is (almost) **never** a good time to use `eval`. – Tyler Roper Oct 08 '18 at 18:51
  • @DuongDang you are right, after converting into JSON.prase ,it works now. var signal = JSON.parse(signal); – Keyme Oct 08 '18 at 18:51

0 Answers0