Home > OS >  how to add a object to an array
how to add a object to an array

Time:11-20

I created a onSubmit event.when i click ADD TO CART button all the data pass to that onSubmit event.then i created a object which is called show.we have these properties in that object.now i want to add that object to an array.

const MainPart = () => {
    const [count, setCount] = useState(0);

    const cart = {
        mark: '$',
        itemNo: 'Item No.  MA000001',
        title: '4 Person tent',
        price: '150.00'

    }

    const submit = (event) => {

        event.preventDefault();

        const show = {
            id: v4(),
            itemNo: cart.itemNo,
            quantity: count,
            title: cart.title,
            currency: cart.mark,
            amount: (cart.price) * (count)
        }

    }

    return (
        <div>
            <form onSubmit={submit}>
                             <Title title={cart.title} itemNo={cart.itemNo} />
                            <Currency mark={cart.mark} price={cart.price} />
                            <Quantity count={count} setCount={setCount} />
                            <div>
                                <input type='submit' value='ADD TO CART'  />
                             </div>
               </form>
 </div>
    );
};

CodePudding user response:

Which array do you want to add your object to? Would it be a stateful array created using useState hook or just a simple array?

You can simply push your object to your array

const submit = (event) => {
  event.preventDefault();

  const show = {
    id: v4(),
    itemNo: cart.itemNo,
    quantity: count,
    title: cart.title,
    currency: cart.mark,
    amount: cart.price * count,
  };

  //Declare your array
  let yourArray = [];

  //This line will add your object to your array

  yourArray.push(show);
};
  • Related