Home > Back-end >  How to get a specific value from an array of object and store them individually ReactJS
How to get a specific value from an array of object and store them individually ReactJS

Time:11-21

I was wondering on how to get a specific value from an array of object.

const [itemList, setItemList] = useState([{
serviceValue:"",
quantityValue:"",
amountToPay:""
}]);

and map them individually from a separate constant/useState. ex.

const [service,setServiceValue] = useState([]); //serviceValue[]
const [quantity,setQuantityValue] = useState([]);//quantityValue[]
const [amountToPay,setAmountToPay] = useState([]);//amountToPay[]

Thank you!

UPDATE

I've used Sir Abhishek's solution by doing this

    const [serviceItem, setServiceList] = useState([{serviceValue:"", 
        quantityValue:"",amountToPay:""}]);
    console.log(serviceItem);

    const [amountToPay, setAmountToPay] = useState([]);
    console.log("AMOUNT TO PAY",amountToPay)
      useEffect(()=>{
        serviceItem.map((item) => (
            setAmountToPay([...amountToPay,item.amountToPay])
        ))
    }, [serviceItem])

The problem now is everytime I change the state of the input, it also records the previous input creating multiple array of object

this is the console.log

The reason why I need the current value of amountToPay is I need the sum by using .reduce

CodePudding user response:

You may use map function for that

itemList.map((item)=>{
setServiceValue([...serviceValue, item.serviceValue]);
setQuantityValue([...itemQuantity, item.quantityValue]);
setAmountToPay([...amountToPay,item.amountToPay]);
})
  • Related