0

I have the code below:

var arrAllBaseJSON = [];
for(var i=0; i < totalCols; i++) {
    var heading = document.getElementById("heading"+i).value;
    var dataType = document.getElementById("dataType"+i).value;
    arrAllBaseJSON['Heading'] = heading;
    arrAllBaseJSON['Type'] = dataType;
    arrAllBaseJSON.push();
    console.log(arrAllBaseJSON)
}

This produces the following in the console.

[Heading: "ID", Type: "Text"]
[Heading: "First Name", Type: "Text"]
[Heading: "Last Name", Type: "Text"]
[Heading: "Month", Type: "Text"]
[Heading: "Cost", Type: "Text"]
[Heading: "DOB", Type: "Text"]

I would like the output to be one array with each loop to be surrounded by braces:

[{Heading: "ID", Type: "Text"},
{Heading: "First Name", Type: "Text"},
{Heading: "Last Name", Type: "Text"},
{Heading: "Month", Type: "Text"},
{Heading: "Cost", Type: "Text"},
{Heading: "DOB", Type: "Text"}]

Would appreciate help!

Jack Ryan
  • 1,287
  • 12
  • 26
user2547766
  • 111
  • 7

3 Answers3

3

Try this

let arrAllBaseJSON = []
for(let i = 0; i < totalCols; i++) {
  let heading = document.getElementById("heading"+i).value;
  let dataType = document.getElementById("dataType"+i).value;
  arrAllBaseJSON.push({
    heading,
    dataType
  });
}
Sherman Hui
  • 938
  • 3
  • 10
  • 22
CodeLover
  • 571
  • 2
  • 11
  • Thanks so much that's doing exactly what I want! Could I ask how I would retrieve just the dataType? I thought the below would work but it's coming up with undefined. console.log(arrAllBaseJSON.dataType) – user2547766 Feb 17 '18 at 09:11
  • 1
    since `arrAllBaseJSON` is an array, you could retrieve each javascript object like `arrAllBaseJSON[i]` then use the dot operator `.` to get the dataType value like `console.log(arrAllBaseJSON[i].dataType);` – CodeLover Feb 17 '18 at 09:13
0

You need to create a new object inside the loop and push it in the array.

var arrAllBaseJSON = [];
for (var i = 0; i < totalCols; i++) {
 var heading = document.getElementById("heading" + i).value;
 var dataType = document.getElementById("dataType" + i).value;
 var obj = {};
 obj['Heading'] = heading;
 obj['Type'] = dataType;
 arrAllBaseJSON.push(obj);
}
console.log(arrAllBaseJSON)
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

Here is how you can do it:

//remove this
var totalCols = 3
var arrAllBaseJSON = [];
for(var i=0; i < totalCols; i++) {
  var heading = document.getElementById("heading"+i).value;
  var dataType = document.getElementById("dataType"+i).value;
  arrAllBaseJSON.push({
    heading: heading,
    dataType: dataType
  });
}

console.log(arrAllBaseJSON);
<input type='text' id='heading0' value='ID' />
<input type='text' id='dataType0' value='Text' /><br/>
<input type='text' id='heading1' value='First Name' />
<input type='text' id='dataType1' value='Text' /><br/>
<input type='text' id='heading2' value='Last Name' />
<input type='text' id='dataType2' value='Text' />
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62