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

124
Views
Use string "array[n]" as variable

I dont know how to really explain this, but here my problem.

i have a string "myKey[2]" and i want to

const values = {
 "myKey": ["hey", "oh"],
 "b": ["something"]
};

const str = "myKey[2]";

My question is : how to get "oh" with a string as a variable name + is there something in js who can read "myarray.key" as variable too without apply many regex and function ?

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

0

As the indexing for the array starts from zero, accessing "myKey[2]" will give you undefined.Assuming you want to take the second element from the array,we can do

const values = {
 "myKey": ["hey", "oh"],
 "b": ["something"]
};

const str = "myKey[1]";

const result=values[str.slice(0, str.indexOf('['))][
  Number(str.slice(str.indexOf('[') + 1, str.indexOf(']')))
];

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

Your string should be

const str = values.myKey[1];

or if your key has dashes and such

const str = values['myKey'][1];

Keep in mind that the right index in this case is 1, not 2 as the index numbering in arrays starts from 0 and not 1.

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!