acer
acer

Reputation: 63

How do I create multiple instances of a object in javascript during runtime?

Trying to finish up an assignment and I can't seem to find get around this: Here's what is being asked:

"Your JavaScript program should parse the user’s inputs. For each input, you should create a JavaScript object of Shopper to hold the data parsed from user’s input. Make sure that each object should have a property named “Items” which should have an string array of items as value, e.g. [“Milk”, “Shoes”, “Phone”]."

Here is what I've done so far:

var shopper = {
  first_name : "",
  last_name : "",
  email  : "",
  items: []
};

var flag = true;
var x = 0;
while (flag == true) {

  var temp_obj = prompt("Please enter your first name, last name, email and items separated by ,");
  if (temp_obj == "" || temp_obj == null) {
    flag = false;
  }

/*Here I'm suppose to create instances of the object..Have no idea how. this is what I think might work.
var shopper[x] = Object.create(shopper);
x++
*/

}

Upvotes: 0

Views: 859

Answers (3)

max
max

Reputation: 102398

There is nothing in the assignment that says that you have to use prompt. It just says.

Your JavaScript program should parse the user’s inputs.

Here is a javascript program which uses a HTML form to create objects.

var form = document.forms[0];
var btn = document.getElementById("create");

btn.onclick = function(event){
  var shopper = {
    first_name: form.first_name,
    last_name: form.last_name
  };
  
  console.log(obj);
  
  event.preventDefault();
};
<link href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.2/css/foundation.css" rel="stylesheet"/>
<form id="shopper_form">
  
  <div class="row">
    <label>First name</label>
    <input type="text" name="first_name"/>
  </div>
  
  <div class="row">
    <label>Last name</label>
    <input type="text" name="last_name"/>
  </div>
  
  <a class="button" href="#" id="create">Create</a>
</form>

<div id="test"></div>

Upvotes: 0

Mulan
Mulan

Reputation: 135415

Here's one way you can do it with a factory function

Click Run code snippet to see it work.

To finish inputting items, click OK with an empty line.

// Shopper constructor
function Shopper(firstName, lastName, email, items) {
  this.firstName = firstName;
  this.lastName  = lastName;
  this.email     = email;
  this.items     = items;
}

// Shopper factory function
// takes user input with comma-separated terms
// inputs[0] = firstName
// inputs[1] = lastName
// inputs[2] = email
// inputs[3..] = items
Shopper.create = function create(str) {
  var inputs = str.split(', ');
  return new Shopper(inputs[0], inputs[1], inputs[2], inputs.slice(3));
};

// a list of all shoppers
var shoppers = [];

// continue collecting user inputs until user enters a blank line
var response;
while (response = prompt("firstName, lastName, email, item1, item2, item3, ...")) {

  // add shopper to the `shoppers` array
  shoppers.push(Shopper.create(response));
}

// display all shoppers
alert(JSON.stringify(shoppers, null, "\t"));

Sample user inputs

a, b, [email protected], milk, candy, eggs
x, y, [email protected], meat, cereal, yams

Output

[
    {
        "firstName": "a",
        "lastName": "b",
        "email": "[email protected]",
        "items": [
            "milk",
            "candy",
            "eggs"
        ]
    },
    {
        "firstName": "x",
        "lastName": "y",
        "email": "[email protected]",
        "items": [
            "meat",
            "cereal",
            "yams"
        ]
    }
]

Upvotes: 2

Oriol
Oriol

Reputation: 288680

You can use the new operator to instantiate a constructor:

function Shopper(str) {
  this.items = str.split(', ');
  this.first_name = this.items[0];
  this.last_name = this.items[1];
  this.email = this.items[2];
}
var str;
while(str = prompt("Please enter...")) {
  var instance = new Shopper(str);
}

Upvotes: 2

Related Questions