I am new to React Hooks
. I have an state
which looks like this.
const [myData, setmyData] = useState([
{
"OrderId": "ord-898s1",
"Shoulder Size": "12",
"Amount": 200,
"Shoulder Width": "2",
},
{
"OrderId": "ord-898s2",
"Shoulder Size": "14",
"Amount": 790,
"Shoulder Width": "2",
}
])
var orderID = "ord-898s2"
var AmountToAdd = 100
I want to update the Amount
Value in orderID ord-898s2
. By adding 100
, the Amount Value in orderID ord-898s2
should be 890
console.log(myData)
Required Output:
[
{
"OrderId": "ord-898s1",
"Shoulder Size": "12",
"Amount": 200,
"Shoulder Width": "2",
},
{
"OrderId": "ord-898s2",
"Shoulder Size": "14",
"Amount": 890,
"Shoulder Width": "2",
}
]
I tried these.
const result2 = myData.map((item) => {
if (item.OrderId === orderID) {
return { ...item, ["Amount"]:item.Amount 100 }
}
return item
})
setmyData(result2)
it failed. I don't know how to make it. Please help me with some solutions.
CodePudding user response:
You could do it like this:
setmyData((prev) =>
prev.map((el) =>
el.OrderId === "ord-898s2" ? { ...el, Amount: el.Amount 100 } : el
)
);
CodePudding user response:
Try below code.
var data = [
{
"OrderId": "ord-898s1",
"Shoulder Size": "12",
"Amount": 200,
"Shoulder Width": "2",
},
{
"OrderId": "ord-898s2",
"Shoulder Size": "14",
"Amount": 790,
"Shoulder Width": "2",
}
];
var orderID = "ord-898s2"
var AmountToAdd = 100
data.forEach((item) =>
item.OrderId === orderID ? item.Amount = item.Amount AmountToAdd : item.Amount);
console.log(data);