Bonitas
Bonitas

Reputation: 13

pushing multiple items into an object array

forgive me, as I am still new so I hope I am explaining this so it makes sense

I wanted to push multiple items into the addItem function (for instance) console.log("forks", "laptop", "juice") I am able to only push in first item. If I split the strings into separate arguments, when I call back the function, I only get the last argument.

  const cart = {
  contents: [],
  addItem(item) {
    cart.contents = (item) 
    contents.push(...item); //tried it with and without the spread operator.
},
  removeItem(deletedItem) {
    delete cart.contents[deletedItem];
  }
};
cart.addItem("laptop");
cart.addItem("guitar");
cart.addItem("phone");
cart.removeItem("guitar")
console.log(`The cart contains: ${cart.contents}`);

Upvotes: 1

Views: 958

Answers (2)

Prince Hernandez
Prince Hernandez

Reputation: 3731

you were pretty close with the spread operator, your code just needed a little change, with this change you can pass multiple items as separated values or even an array with multiple items, even multiple arrays with multiple values.

they end always being a plain array of strings, here is your working code.

const cart = {
  contents: [],
  addItem: (...items) => {
    cart.contents = [...cart.contents, ...items];
  },
  removeItem(deletedItem) {
    this.contents.splice(this.contents.indexOf(deletedItem), 1);
  }
};

// multiple values
cart.addItem("laptop", "guitar", "phone");
console.log(`The cart contains: ${cart.contents}`);

// array of values
cart.addItem(['new laptop', 'new guitar', 'new phone']);
console.log(`The cart contains: ${cart.contents}`);

// multiple arrays
cart.addItem(['inner laptop1', 'inner guitar1', 'inner phone1'], ['inner laptop2', 'inner guitar2', 'inner phone2'], ['inner laptop3', 'inner guitar3', 'inner phone3']);
console.log(`The cart contains: ${cart.contents}`);

Upvotes: 1

Spectric
Spectric

Reputation: 32002

You have to make item a rest parameter:

const cart = {
  contents: [],
  addItem(...item) {
    this.contents.push(...item);
  },
  removeItem(deletedItem) {
    this.contents.splice(this.contents.indexOf(deletedItem), 1);
  }
};
cart.addItem("laptop", "guitar", "phone");
cart.removeItem("guitar")
console.log(`The cart contains: ${cart.contents}`);

Also, don't use delete to delete an item. Instead, use splice().

Upvotes: 1

Related Questions