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!

0

3 Answers 3

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
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

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)
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);
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)

Comments

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' />

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.