1

I want to create a new "product" object and specify its properties (name, and etc), through the function "addProduct"

var storage = [
    {product: {name: "cat", count: 3443, price: 1000}}
    
];

function addProduct(newProduct) {
    var newProduct =  this.product;
}
var addProd = new addProduct("dog", 1488, 2000);
Igor Shvets
  • 547
  • 6
  • 15
  • Possible duplicate of [What is the 'new' keyword in JavaScript?](https://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript) – Julius Dzidzevičius Apr 29 '18 at 11:45

3 Answers3

1

Here is one way to do it if I understood your correctly:

var storage = [
    {product: {name: "cat", count: 3443, price: 1000}}
    
];

function addProduct(newProduct) {
    storage.push(newProduct);
    console.log(storage);
}

addProduct({name: "dog", count: 1488, price: 2000});
Isma
  • 14,604
  • 5
  • 37
  • 51
1

Are you talking about creating objects with "constructor" ?

function Product(name, count, price) {
  this.name = name;
  this.count = count;
  this.price = price;
}

var product = new Product("dog", 1488, 2000);

console.log(product) // { name: "dog", count: 1488, price: 2000 }
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
0

You can either addProduct or updateProduct using below code:

var storage = [
    {product: {name: "cat", count: 3443, price: 1000}}

];

function addProduct(newProduct) {
    storage.push(newProduct)
    return true;
}

function updateProduct(prodLoc, updatedProduct) {
    storage[prodLoc] = updatedProduct;
    return true;
}

console.log(addProduct({"dog", 1488, 2000}));
console.log(updateProduct(0, {"updateDog", 1466, 1999}));
Karthik S
  • 313
  • 2
  • 7