0

I have this array in the global scope:

const orders = [];

I want to push an object to this array.

const addItem = ($id, $name, $price) => {
  const $item = ({
    id: $id,
    name: $name,
    price: $price,
    amount: 1
   });
  orders.Push = $item;
  return orders;
 };

The thing is that I want to push an object into the array after every clickevent. For now it only adds 1 object to the array for the first clickevent, but after I click another time, it won't push anymore.

FoxOnFireHD
  • 145
  • 11
  • `Push` ?? is your custom function. I can't see any `array.push()` here .Where you are pushing it? – Shubham Dixit Oct 22 '19 at 18:07
  • 1
    ``orders.Push = $item`` will not push anything. It will replace the contents of ``orders.Push`` with ``$item``. If ``orders.Push`` is supposed to be an array, try ``orders.Push.push( $item )``. – kmoser Oct 22 '19 at 18:08
  • 1
    I think what you intended to do was `orders.push($item)` instead of `orders.Push = $item`. – slider Oct 22 '19 at 18:10
  • 2
    Possible duplicate of [How to append something to an array?](https://stackoverflow.com/questions/351409/how-to-append-something-to-an-array) – slider Oct 22 '19 at 18:11
  • Hmmm... well if this code is actually pushing something into that array the first time as you state, then you must be using some framework that maps that orders.Push = $item to orders.push($item). So if that is working then it must be how you are implementing it. Can you post your code that actually calls the 'addItem' function? – Kyle Oct 22 '19 at 18:19
  • This looks like a reducer, so you could actually call reduce and return the concatenation of `orders`... – Mr. Polywhirl Oct 22 '19 at 18:30

2 Answers2

0

orders.Push = $item may assing a value to Push like [Push: $item] and will replace the Push value on next call of function.

The correct way to use this can be as

const orders = [];
const addItem = ($id, $name, $price) => {
  const $item = {
    id: $id,
    name: $name,
    price: $price,
    amount: 1
   };
  orders.push($item);
  return orders;
 };
0

It's a bit unorthodox, but I managed to use your code, unmodified to obtain a reasonable result.

// ▼ ============= No Changes ============= ▼
const orders = [];
const addItem = ($id, $name, $price) => {
  const $item = ({
    id: $id,
    name: $name,
    price: $price,
    amount: 1
  });
  orders.Push = $item;
  return orders;
};
// ▲ ============= No Changes ============= ▲

[
  { id : 1, name : 'foo', price : '1.00' },
  { id : 2, name : 'bar', price : '2.00' }
].map((data) => {
  addItem(data.id, data.name, data.price);
  orders.push(orders.Push); // Let's push "Push" onto the array...
});

console.log(orders); // Log the result...
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132