0

I have a object Node that has multiple attributes and an attributes array that is filled with the names of those attributes. I want to go through a for loop and populate a form using the attributes values from the node. The code is below:

function Node(parentNode, nodeID, fields, type){
    this.id =  nodeID;
    this.fields = fields;
    this.parent = parentNode;
    this.type = type;
    this.firstChild = null;
    this.lastChild = null;
    this.previousSibling = null;
    this.nextSibling = null;
}

var runTerminalNode = function(node, count){
    var form = document.createElement('form');
    form.setAttribute('method', 'GET');
    form.setAttribute('action', '/table/');
    form.setAttribute('target', '_blank');

    var attributes = ['id', 'fields', 'type']

    for (i in attributes){
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = attributes[i];
        input.value = node.attributes[i];
        form.appendChild(input);
    }
}

var nodeObject = allNodes[nodeID];
runTerminalNode = (nodeObject, 0);

Where allNodes, is a map where the nodeID is the key and the Node object is the value.

The error I'm getting is "Cannot read property '0' of undefined" as node.attributes is resolving to undefined and it's trying to read the first object in the undefined array. What I want is it to read it as node.id, node.fields, and node.type. Does anyone know a way to address this?

jarsushi
  • 57
  • 5

1 Answers1

1
 for (i in attributes){

This iterates over the arrays keys (0, 1, 2), and they are not part of the object. Additionally i is a global variable, which is bad for various reasons. The next problem is here:

node.attributes[i]

This looks for the "attribute" property in node node for the value at position i of the attributes, that would be:

node[ attributes[i] ]

Might instead iterate over the values and declare the variable:

for(const attr of attributes)
  console.log(node[attr]);

If you really want to iterate over the indices, just do:

for(const index of array.keys())
// OR
for(const [index, value] of array.entries())

read on:

Iterating an array

Dot notation vs. Bracket notation

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151