0

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?

1
  • If I understand your question right, you can access properties like []. For example SomeObject["someProperty"] or in your case SomeObject[INDEX] Commented Dec 1, 2021 at 2:06

2 Answers 2

2

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


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.

Sign up to request clarification or add additional context in comments.

Comments

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

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

3 Comments

Wrong syntax. Supposed to be let result = data?.first?.second?.[`FOO_${theIndex}`]?.name;
i just try one and it's okay,
Backticks for template literals DO NOT mix with normal strings. Also see the TC39 proposal for optional chaining. It goes something like this: obj?.[index]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.