JSFiddle - React, Tailwind, and code Playground

by fillano

HTML

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物件比對值</title>
  </head>

  <body>
    <label for="id">ID</label>
    <input type="text" id="id">
    <br>
    <label for="amount">數量</label>
    <input type="number" id="amount">
    <button id="button">push</button>

    <script>
      const prod = [{
          id: '2',
          amount: 3
        },
        {
          id: '1',
          amount: 2
        },
        {
          id: '3',
          amount: 10
        }
      ]
      const button = document.getElementById('button');
      const amount = document.getElementById('amount');
      const id = document.getElementById('id');
      const itemList = [];

      function clickHandler() {
        if (id.value) {
        	let found = itemList.find(p => p.id == id.value);
          if(found && amount.value) {
          	found.amount += parseInt(amount.value, 10);
          } else {
          	let matched = prod.find(p => p.id == id.value);
            if(amount.value) {
            	matched.amount += parseInt(amount.value, 10);
            }
            itemList.push(matched);
          }
        }
        console.log(itemList);
      }

      button.addEventListener('click', clickHandler);

    </script>

  </body>

</html>