How to concatenate Object to specific object in Array of Objects in useState React Hooks

Viewed 197

I am new to reactjs. I have used state in react hooks. I have declared a state which is shown below

const [data1, setData1] = useState([{"orderID":"o1"},{"orderID":"o2"}])

I have declared a orderID with number o2

var orderID = "o2"

I have another state data

const [data2, setData2] = useState({"Waist":"3", "Hip":"2"})

I want to update the data2 object to data1 array of objects which has the OrderID of o2

Required Output:

console.log(data1)

[{"orderID":"o1"},{"orderID":"o2", "Waist":"3", "Hip":"2"}]

I want to set the Object to data1 state. I don't know how to make it. I have searched Stack Overflow. But I can't find Solutions. Please Help me to solve this problem

1 Answers

Try this approach.

setData1(prevData1 => 
    prevData1.map(element => element.orderID === orderId ? ({
        ...element,
        ...data2
    }) : element))
Related