Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Change variable with string instead of just accessing it

I can access a variable easily:

function accessVariable(accessFunction, variable) {
    var namespaces = accessFunction.split(".");
    for (var b = 0; b < namespaces.length; b++) {
        if (namespaces[b] != "") {
            try {
                variable = variable[namespaces[b]];
            } catch {
                variable = undefined;
            };
        };
        return variable;
    };

But updating this gotten variable is something that I don't know how to do.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It's easiest if you use a separate function to update. This can take the new value as another argument.

Then you stop the iteration before the last item in namespace, and use that as the index to assign to.

function updateVariable(accessFunction, variable, value) {
  var namespaces = accessFunction.split(".");
  for (var b = 0; b < namespaces.length - 1; b++) {
    if (namespaces[b] != "") {
      try {
        variable = variable[namespaces[b]];
      } catch {
        variable = undefined;
      }
    }
  }
  if (variable) {
    variable[namespaces.pop()] = value;
  }
}

let obj = {a: {b:[{c: 10}]}};
updateVariable('a.b.0.c', obj, 20);
console.log(obj);

about 4 years ago · Juan Pablo Isaza Report

0

Define a single global-scoped variable, and put your variables there.

var Glob = {}; // globally scoped object

function changeVar(){
    Glob.variable1 = 'value1';
}

function SeeVar(){
    alert(Glob.variable1); // shows 'value1'
} 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!