Ed Villa
Ed Villa

Reputation: 69

javascript how to creat array of objects

I have a project I am working, one part of the project requires it to use an array of objects. I understand what an array is and also understand how to create an object. I created a new object named student with properties of name, grade and student ID. each one of these object propperites will be generated by user in input text fields. I have a button that I use to save every entry into an array but do not understand how to incorporate my student object into my array or not understanding properly what an array of objects is which is requirement for this project. I already had it set up to work with a parallel array and commented out lines to add my new student object and new student ID input field but now I am stuck. I researched it and am not getting information needed to complete this task or it is not very clear. This is what I have so far

<br>
<p><b>Student Name:</b></p>
<input id="inp" type="text">
<br>
<br>
<p><b>Grade:</b></p>
<input id="inps" type="text">
<br>
<br>
<p><b>Student ID:</b></p>
<input id="inpsid" type="text">
<br>
<br>
<button type="button" onclick="enter()">Enter</button>
<br>
<br>
<button type="button" onclick="construct()">Constructor</button>
<p>Student Names List:</p>
<p id="iop"></p>
<br>
<p id="opo"></p>
<br>
<p id="hop"></p>
<br>
<p id="lop"></p>
<br>
<p id="aop"></p>
<br>
<p id="cop"></p>
<br>
<script>

    var studentArr = new Array();
    var scoreArr = new Array();

    function enter() {

        var student = {
        name : document.getElementById("inp").value,
        grade : "A",
        id : 001
        };

        // Just to test my object property is saving input correctly.
        document.getElementById("iop").innerHTML = student.name;

        studentArr.push(student.name);

        var stuval = "";

        for(i=0; i < studentArr.length; i++)
        {
            stuval = stuval + studentArr[i] + "<br/>";
        }

        }

  </script>

Upvotes: 0

Views: 699

Answers (1)

Abdul Shaikh
Abdul Shaikh

Reputation: 129

an array of objects is pretty simple to create in JS. it can be done kinda like this:

var objs = [{name:"fname",dob:"1/17/1999"},{name:
"guy",dob:"2/14/1962"}];

we can also push objects to the array like so:

objs.push({name:"new name", dob:"4/26/1987"});

to collect object property values from user input we can do something like this.

var input = document.getElementById("inp").value;

objs.push({name:input,grade:80, sid:001});

This will allow us to grab the value from a text input and push it to our object.

Upvotes: 1

Related Questions