Home > database >  From a array make a new object data and send it to new array in react functional component
From a array make a new object data and send it to new array in react functional component

Time:07-06

I have fetched data from the backend where I have products in the array. So, now I want to make new data object and push it to a new array from that fetched data.

fetched data is like

(3) [{…}, {…}, {…}]
0:
createdAt: "2022-06-29T15:53:41.783Z"
orderPrice: 500
orderQuantity: 25
productId: {_id: '62bc5c6a6cfcd59cb2ee6b86', name: '6000Hz sound box', slug: '6000hz-sound-box', price: 1500, quantity: 500, …}
updatedAt: "2022-06-29T15:53:41.783Z"
_id: "62bc758508150c97aa815c14"
[[Prototype]]: Object
1: {_id: '62bc8a2ffe76ecd817bfcd50', productId: {…}, orderPrice: 50, orderQuantity: 10, createdAt: '2022-06-29T17:21:51.473Z', …}
2: {_id: '62c2f805923a5feb6bdb89b6', productId: {…}, orderPrice: 50, orderQuantity: 20, createdAt: '2022-07-04T14:24:05.981Z', …}
length: 3

Now from this data, I want to make like this object and for every item, it will push to a new array

{ productId: item.productId._id, perProductTotal: item.orderQuantity * item.orderPrice, orderPrice: item.orderPrice, orderQuantity: item.orderQuantity }

My expected result, If I have 3 items in the cart like in the image then the data should be like this

newArray = [
       {
            "productId": "62bc5c6a6cfcd59cb2ee6b86",
            "perProductTotal": "4500",
            "orderPrice": "1500",
            "orderQuantity": "3"
        },
        {
            "productId": "62bc5c9e6cfcd59cb2ee6c6c",
            "perProductTotal": "180000",
            "orderPrice": "90000",
            "orderQuantity": "2"
        },
        {
            "productId": "62bc5c9e6cfcd59cb2ee6c6c",
            "perProductTotal": "180000",
            "orderPrice": "90000",
            "orderQuantity": "2"
        }
]

I have tried this type of solution but I did not get the expected result,

useEffect(() => {
        if (cartItems?.success === true) {
            cartItems?.cartItems.map(item =>  (
                //cartProducts.push = { ...cartProducts,
                //     productId: item.productId._id, perProductTotal: item.orderQuantity * item.orderPrice, orderPrice: item.orderPrice, orderQuantity: item.orderQuantity
                // }

                // setCartProducts = ({ ...cartProducts,
                //     productId: item.productId._id, perProductTotal: item.orderQuantity * item.orderPrice, orderPrice: item.orderPrice, orderQuantity: item.orderQuantity
                // })
            ))
            
        }
    }, [cartItems])

CodePudding user response:

I'm going to assume that you are storing your API call in cartItems based on your code and that you want to store the cleaned array in cartProducts. Here is how I would do it:

  useEffect(() => {
    // This simplified version checks for truthy, same as === true
    if (cartItems?.success) {
      cartItems?.cartItems.map(item => {
        let joinedArray = cartProducts.concat({
          productId: item.productId._id, 
          perProductTotal: item.orderQuantity * item.orderPrice, 
          orderPrice: item.orderPrice, 
          orderQuantity: item.orderQuantity
        })
        setCartProducts(joinedArray)
      })
    }
  }, [cartItems])

This should add to the array on each loop.

CodePudding user response:

How do you fetch data from backend ? Do you also use a useEffect ?

If you use a useEffect with await like

useEffect(() => {
   const fetchData = async () => {
       const cartItems = await API.getCartItems();
       setCartItems(cartItems);
   }
   fetchData();
}, [])

You can put you transform function after data fetching, before setting cartItems :

const transformData = () => {
     const newArray = [];
     // put your map function here
     return newArray;
}

useEffect(() => {
   const fetchData = async () => {
       const cartItems = await API.getCartItems();
       const cartProducts = transformData(cartItems);
       setCartProducts(cartProducts);
   }
   fetchData();
}, [])
  • Related