使用 Immutability helper js 更新对象数组中对象内的元素

Update a element inside object in aobject array with Immutability helper js

我需要使用 Immutability helper

添加或减去对象数组中元素的值
const selectedFood= [
{id: uuidv4(), name: "pizza", price: 1700, amount: 3},
{id: uuidv4(), name: "cheese", price: 600, amount: 10},
{id: uuidv4(), name: "fried rice", price: 500, amount: 4},
{id: uuidv4(), name: "coke", price: 100, amount: 5}]


const [foodArray, setFoodArray] = useState(selectedFood);

这段代码完美无缺,这就是我想要的除了索引

setFoodArray((prev) => {
                 return update(prev, {2: {amount: {$apply: function(x) {return x -1}}}})
        })

这里的数字2应该是索引

所以我用它来获取索引

const index = foodArray.indexOf(foodArray.find((single) => {
            return single.id === id
        }));

把这个索引变量放在那里是行不通的

setFoodArray((prev) => {
                 return update(prev, {index: {amount: {$apply: function(x) {return x -1}}}})
        })

Picture for understanding better

谁能帮忙

使用括号表示法:

setFoodArray((prev) => {
    return update(prev, {[index]: {amount: {$apply: function(x) {return x -1}}}})
})