Search code examples
javascriptarraysvariablesnaming

Naming; dynamically create a variable in javascript


To avoid a javascript heap problem, I use multiple arrays: family1, family2,family3 ..., dogs1, dogs2, dogs3 ... Use example: 'family1 and dogs1', or 'family132 and dogs132' to create a new array 'results'.

How do I pass the "id" correctly

let  id = 'value here'
this.family + id
this.dogs + id

So far my str itself is pushed int the new array: t-h-i-s-.-f-a-m-i-l-y-1

for (let i = +0; i < +20; i++) {

  const id = 1;
  let str = 'this.family'+id;   // ?
  let str = 'this.dogs'+id;   // ?

  console.log(str);

  const result = {
      familyType: str[i],       // behavior: t-h-i-s-.-f-a-m-i-l-y-1
      protocol: this.dogs1[i],  // expected original behavior
  };

  results.push(result);

}

}

Solution

  • You are looking for:

    let str = this['family'+id]; 
    

    But this is generally a bad design pattern. Don't name your variables with incremental numbers. Use 2D arrays (i.e. arrays having arrays as values), like this.dog[id][i]. If you have "a javascript heap problem", then it is caused by some other code.