How can I Create a Variable based on other variables' names? For example if i have a variable named 'a' then i want to create a new variable and name it 'a2'. And if the variable a2 exists then I want to create another one called 'a3' etc... how can I achieve this with javascript?
Asked
Active
Viewed 82 times
0
-
Are you using [modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) or global context (regular javascript tags)? – Mosh Feu Jun 07 '20 at 11:13
-
5What are you trying to accomplish? It sounds like you want to use an array or list rather than actual variables? Can you give an example of what you are trying to accomplish? – Patrick Jun 07 '20 at 11:14
-
1This should help you https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – vrachlin Jun 07 '20 at 11:14
-
1See this: https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript. – Saurabh Agrawal Jun 07 '20 at 11:18
-
1You never need or want dynamic variable names. Please use an object instead, or an array, e.g. `const a = [3, 4, 5]; console.log(a[1], a[2]); a.push(6); console.log(a[3]);`. See [Use dynamic variable names in JavaScript](https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript). – Sebastian Simon Jun 07 '20 at 11:18
-
The answers in question https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript just name the variables based on their contents what I wanted was to name variables based on the NAME of the other variables – Mohamed Technology Jun 07 '20 at 11:43
-
@user4642212 Thanks I'll Use arrays/objects instead – Mohamed Technology Jun 07 '20 at 11:54
1 Answers
0
You want an array. Use an array. However, that being said, here's a disgusting hack to generate new properties.
function incrementName(old_name) {
// check for number at end of name
const number_match = old_name.match(/\d$/);
if (number_match) {
// increment number at end
const next_num = ''+(Number.parseInt(number_match[0])+1);
return old_name.substr(0,number_match.index) + next_num;
}
else {
// otherwise just add a 2
return old_name+'2';
}
}
function getUnusedName(object,original_name) {
let name = original_name;
while (name in object) {
name = incrementName(name);
}
return name;
}
// usage
const my_object = {
'a':'boo',
'b2':'bar'
}
my_object[getUnusedName(my_object,'a')] = 'foo';
my_object[getUnusedName(my_object,'b2')] = 'baz';
console.log(my_object);

Ted Brownlow
- 1,103
- 9
- 15
-
Thanks For Your answer This seems To be What i Was looking For – Mohamed Technology Jun 07 '20 at 11:52