Home > OS >  how can I dynamically get the variables in javascript?
how can I dynamically get the variables in javascript?

Time:12-01

I am working on React app, but I think this is most likely JavaScript problem. I have many variables with a pattern, VARIABLE_NAME_{number}, example, FOO_1, FOO_2 ... so on. In my function, it takes index as input and return mapped output.

import power from 'customClass';
const getOneOfFoo = (theIndex) => {
  power()
   .then(data => {
      let result = data?.first?.second?.FOO_{theIndex}?.name ; // how can I declare this one with passing input?
     // example, if theIndex=59, I want to have
     // let result = data?.first?.second?.FOO_59?.name;
      resolve({
          result: result
      });
     })
   .catch(err => console.log(err))
  });

The data object structure is like this,

data
 |-first
     |-second
         |-FOO_1
            |-name
         |-FOO_2
            |-name
         |-FOO_3
            |-name
         |-FOO_4
            |-name
         ...

In line 5, I want to assign result dynamically. How can I achieve this?

CodePudding user response:

You can treat it like a dictionary. Here's an example:

const data = {
  'FOO_1': { name: 'Kenobi' },
  'FOO_2': { name: 'Skywalker' },
  'FOO_3': { name: 'Yoda' },
  'FOO_4': { name: 'Kylo' },
  'FOO_5': { name: 'Sidious' }
}

function getVar(index) {
  let result = data?.[`FOO_${index}`]?.name;
  return result;
}

console.log(getVar(1)); // expected output: Kenobi
console.log(getVar(2)); // expected output: Skywalker
console.log(getVar(3)); // expected output: Yoda
console.log(getVar(4)); // expected output: Kylo
console.log(getVar(5)); // expected output: Sidious
console.log(getVar(6)); // expected output: undefined
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>


So for your case, it would probably be something like this:

import power from 'customClass';
const getOneOfFoo = (theIndex) => {
  power()
   .then(data => {
      let result = data?.first?.second?.[`FOO_${theIndex}`]?.name;
      resolve({
          result: result
      });
     })
   .catch(err => console.log(err))
  });

And btw, resolve doesn't seem to be defined.

CodePudding user response:

let result = data?.first?.second[`FOO_${theIndex}`]?.name ;

u can use [] with inside is string which is name of property

  • Related