0

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++
*/

}
2
  • 1
    You may find this and that links very useful. The answer to your question (and more) are in those links. Good luck =] Commented Jun 21, 2015 at 22:21
  • 1
    You cannot create an "instance of an object". An object is already an instance. Commented Jun 21, 2015 at 22:51

3 Answers 3

2

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

9 Comments

I'd like to see a validation of the input before the Shopper is created if (inputs.length >= 4). Also, the create function will be needlessly replicated on every Shopper object
@Jan, I don't write defensive software, nor do I recommend it. There's always a better way.
@Jan, you are wrong. The Shopper.create function exists as a property of the Shopper constructor function. Each instance will not inherit the property. But, even if it was attached to the Shopper.prototype, it still would only exist as a single function. -- You can think of this difference as class methods vs instance methods in traditional OOP.
Yeah I stand corrected, I had my prototypes all mixed up. Damn, long since I worked with them. What's your beef with defensive programming? Granted, not a fan of validation myself but thought that in this case it would be warranted. Maybe not the right place to do it though...
Nice answer Naomik. However, I want to be able to make instances like this: shopper1.first_name = joe; shopper2.first_name = dan; I need to manipulate the values in each instance of the object later in the assignment. You answer seem to have array of shoppers
|
2

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

2 Comments

Surely parsing of the input shouldn't be the responsibility of the class constructor like that.
Probably true, but here the parsing is so simple that I don't think it matters much.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.