Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get each variable from class in a for loop

I’m creating an interpreter that reads

variable1: 2
variable2: 400
variable3: 31

from a text file, and initializes the variables on runtime. using eval() and Regular Expressions

class Rules{
    getSegmentArgs_string(sgmnt, scope)
    {
        let argarray = new Array;
        let vardeclaration;
        for(let i=0; i<this.rules[sgmnt].length; i++)
        {
            let regexp = /(\w+): ([0-9\.]+)/g;
            for (const match of this.rules[sgmnt][i].matchAll(regexp)) {
                vardeclaration = (scope+match[1].toString() + " = "+match[2].toString()+";");
                argarray[i] = vardeclaration;
            }
        }
        return argarray;
    }
    setSegment(sgmnt)
    {
        this.segment = sgmnt;
    }
    init()
    {
        this.defaultvars = this.getSegmentArgs_string(this.segment,"this.")
        for(let i=0; i<this.defaultvars.length; i++)
        {
            eval(this.defaultvars[i]);
        }
        delete(this.rules);
        delete(this.defaultvars);
        delete(this.segment);
    }
    constructor() {
        this.rules = this.dump();
    }
}
let rules = new Rules;
rules.setSegment(3);
rules.init();

However, I can not understand how to access these initialized variables in a for loop that dumps each variable’s name, as well as its’ value

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (const variables in rules)
{
          console.log({variales});
          console.log({variables}.value);
}

I’m capable of accessing the value when doing

console.log(rules.variables1,rules.variables2,rules.variables3)

but due to the nature of the task, I need to loop through all variables without naming them in code.

>Solution :

for…in gives you the key of the object properties. You have to access the value with the key

for (const key in rules)
{
      console.log(key, rules[key]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading