Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
How to access object with a randomly chosen name stored in a variable?

I've got 16 objects with names like: aBoard, bBoard, cBoard and so on, eg. let aBoard = { currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true };

I have an array of corresponding names, randomly chose one of them and change it so it matches the name of one of the objects.

const BOARDARRAY = ["unitA", "unitB", "unitC", "unitD", "unitE", "unitF", "unitG", "unitH", "unitI", "unitJ", "unitK", "unitL", "unitM", "unitN", "unitO", "unitP"];

let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
let temp = (currentBoardTile.charAt(currentBoardTile.length -1).toLowerCase());
JSObjectBoardUnit = (temp + "Board");

How to access the object using my JSObjectBoardUnit? In other words, how to make JS "understand" that I want to treat JSObjectBoardUnit value (string) as a value of the object address?

Eg. Let's day JSObjectBoardUnit = aBoard; Basically the outcome I want is: aBoard.key1 = JSObjectBoardUnit.key1. I'd love to use the value stored in JSObjectBoardUnit to access the name of the predefined object aBoard.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I'm not sure to understand well your question but I think this 2 methode could maybe help you.

You can access attribute of a object with a string by using

const obj = {toto: 1};
const name = "toto";
console.log(obj["toto"]); // 1
console.log(obj[name]); // here we use variable and the result is 1

so you could store all yoyr object inside one and do this.

const allBoard = {
"aboard": null, // do not put null use your board
}

console.log(allBoard[(temp + "board")]); // display the temp + board attribute so if temps is equal to a then it will get the aboard

this is what you want, getting object from a string.

But I saw that the aboard also have an id attribute with "unitA" Instead you could build an array of aboard, bboard ....

and use the Array.find() methode that will return the object that match the condition.

in your case

const myBoardArray = [{ currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true }, ....];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];

myBoardArray.find((board) => board.ID === currentBoardTile);
about 4 years ago · Juan Pablo Isaza Relatório

0

2 options

  1. Put the boards in a list, and iterate over them with a for loop. In the for loop, use an if statement to see which Id matches the board you want.
let boards = [aBoard , bBoard, cBoard];
boards.forEach(board=> {
    if (board.ID == currentBoardTile) {
        //do something
    }
});
  1. Create a dictionary where the key is the board id and the respective object is the value. Use the board id to get the respective value.
var boards = { 
    "unitA" : boardA, 
    "unitB" : boardB, 
    .... 
}; 
currentBoardTile = BOARDARRAY[randomizer]; 
console.log(currentBoardTile + " : " + boards[currentBoardTile]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda