Search code examples
javascriptarraysrecords

Add element to array of records


Sorry I am new to JS. I have found references to .push to add an element to an array and using 'function' to define the structure of an object but I want to keep the code as simple as possible for teaching!

Here is my code:

"use strict";
var ListItem = {
  field1: "",
  field2: 0
};
var DataList = [{
  field1: "",
  field2: 0
}];


for (var x = 0; x < 3; x++) {
  DataList.push(ListItem)
  DataList[x].field1 = prompt("item " + x + " Enter f1 data:");
  DataList[x].field2 = prompt("item " + x + " Enter f2 data:");
}
for (x = 0; x < 3; x++) {
  document.write(x + ": " + DataList[x].field1 + " and " + DataList[x].field2 + "<br/>");
}

This is just the latest iteration of my trial and error.

I would like to create an array of a structured data type and then dynamically add elements to it. I have tried several alternatives to line 7 (DataList.push), such as DataList[x] = ListItem;

Sorry if this has been asked before but I cannot find a simple solution!


Solution

  • Those two declarations at the top don't seem to do much, and you don't have to pre-declare your fields in JavaScript.. This should do the trick:

    "use strict";
    var dataList = []; 
    
    for (var x=0;x<3;x++) {
        dataList.push({}) // make new object
        dataList[x].field1 = prompt("item " + x + " Enter f1 data:");
        dataList[x].field2 = prompt("item " + x + " Enter f2 data:");
    }
    for (x=0;x<3;x++) {
        document.write(x + ": " + dataList[x].field1  + " and " + dataList[x].field2 + "<br/>");
    }
    

    Though, it should be mentioned that this is a pretty horrible thing to do..