Benny Smarty
Benny Smarty

Reputation: 45

How to add element to an Object?

JavaScript:

let stock = {
1001: {product: 'Chocolates', cost: 10, quantity: 0},
1002: {product: 'Biscuits', cost: 10, quantity: 0},
1003: {product: 'Bread', cost: 20, quantity: 0},
1004: {product: 'Milk', cost: 25, quantity: 0},
1005: {product: 'Curd', cost: 20, quantity: 0},

}

So, on the JavaScript side, I have declared an object, "stock". Now using HTML's prompt as input I want to add the input code, product, cost, and quantity.

HTML:

<body>
<h1>My Shop</h1>
<label for="numberOfNewProducts" id="numberOfNewProductsLabel">Enter the Number of New Products to be Added: </label>
<br>
<input type="text" id="numberOfNewProducts" value="" placeholder="Enter the number of new Products to be added">
<button type="button" class="btn btn-default" id="addButton" onclick="addProduct()">Add</button>
<script src="stock.js"></script>
<script>
    function addProduct(){
        let numberOfNewProducts = document.getElementById("numberOfNewProducts").value;
        Number(numberOfNewProducts);
        number = 0;
        while(number < numberOfNewProducts){
            number++;
            let inputCode = prompt("Entert the Code you want to give to the New Product: ");
            Number(inputCode);
            let inputProductName = prompt("Enter the Name of the New Product: ");
            let inputProductCost = prompt("Enter the Cost of the New Product: ");
            Number(inputProductCost);
            let inputProductQuantity = prompt("Enter the Quantity of the New Product: ");
            Number(inputProductQuantity);
            stock[inputCode].product = inputProductName;
            stock[inputCode].cost = inputProductCost;
            stock[inputCode].quantity = inputProductQuantity;
            console.log(stock);
        }
    }
</script>

The end of the while loop is a little perplexed also. How do I add the input code and all the products, cost and quantity to the object, "stock"?

Upvotes: 1

Views: 71

Answers (1)

Adnan karim
Adnan karim

Reputation: 1067

Just create a object like:

var obj = {product:"Cookie",cost:10,quantity:0};

then add into the stock like:

stock[inputCode] = obj;

Upvotes: 2

Related Questions