Search code examples
javascriptarraysmutability

Specifying a variable as an array destination in Javascript ( mutability? )


I have 5 arrays in Javascript that I’ll fill and whichever array I fill will depend on the value of “x”. I am getting hopelessly confused regarding variable usage/mutability here. My code is below….

//Node arrays that hold the IDs of each node
nodeOne = [];
nodeTwo = [];
nodeThree = [];
nodeFour = [];
nodeFive = [];
var nodesButtonToNode = {pn_btn_1:"nodeOne", pn_btn_2:"nodeTwo", pn_btn_3:"nodeThree", pn_btn_4:"nodeFour", pn_btn_5:"nodeFive"};

x = "pn_btn_1"; 

nodesButtonToNode.x.push("I am supposed to go into nodeOne")

In a nutshell if x = “pn_btn_1” that would then pull the value of the array that needs to be filled by specifying the key in nodesButtonToNode. In this case that array would be nodeOne. If x = “pn_btn_2” then the area that would need to be added to would be nodeTwo. As expected I am getting lots of undefined errors and I'm not sure where I'm going wrong.

Many TIA for any pointers


Solution

  • You should use an object with the array names as the keys, then you can access them via bracket obj[var] notation:

    //Node arrays that hold the IDs of each node
    const nodes = {
      nodeOne: [],
      nodeTwo: [],
      nodeThree: [],
      nodeFour: [],
      nodeFive: []
    };
    
    var nodesButtonToNode = {
      pn_btn_1: "nodeOne",
      pn_btn_2: "nodeTwo",
      pn_btn_3: "nodeThree",
      pn_btn_4: "nodeFour",
      pn_btn_5: "nodeFive"
    };
    
    x = "pn_btn_1";
    
    nodes[nodesButtonToNode[x]].push("I am supposed to go into nodeOne");
    
    console.log(nodes);