gpt4 book ai didi

angular - ngrx更新数组内的对象

转载 作者:行者123 更新时间:2023-12-03 15:27:32 25 4
gpt4 key购买 nike

我有一个带有对象数组的ngrx存储。我正在寻找的是使用数组索引更新(修改)数组内部的对象。
我的ngrx数据看起来像

    policies: {
beneficiaries: {
beneficiaries: [{
name: 'pqr'
age: 56
},
{
name: 'xyz'
age: 76
}
]
}
}

我必须根据数组索引更新受益人名称。
所以我实现了以下reduce函数
    on(policiesActions.updateBeneficiaryPercentage, (state, action) => {
return {
...state,
beneficiaries: {
...state.beneficiaries,
beneficiaries: {
...state.beneficiaries.beneficiaries,
[action.index]: {
...state.beneficiaries.beneficiaries[action.index],
name: action.value
}
}
}
};
})

上面的代码的问题是
运行此代码后,我商店的结构将更改为
policies: {
beneficiaries: {
beneficiaries: {
0: {
name: 'pqr'
age: 1000
},
1: {
name: 'xyz'
age: 76
}
}
}
}

请帮助我修复代码,以便我可以在不更改商店结构的情况下更新值。

最佳答案

当更新数组中的对象时,我将重新创建一个包含所有排除对象的数组,并追加需要更新值的最后一个对象。

const policies = {
beneficiaries: {
beneficiaries: [{
name: 'pqr',
age: 56
},
{
name: 'xyz',
age: 76
}
]
}
}

const updateObject = (state, action) => {

if(!state.beneficiaries.beneficiaries[action.index]) {
return state;
}

return {
...state,
beneficiaries: {
...state.beneficiaries,
beneficiaries: [
...state.beneficiaries.beneficiaries.slice(0, action.index),
{
...state.beneficiaries.beneficiaries[action.index],
name: action.value
},
...state.beneficiaries.beneficiaries.slice(action.index + 1)
]
}
};
}

console.log(updateObject(policies, {index: 1, value: 'test'}))


- 编辑

添加了代码段并更改了逻辑,因此它不会更改列表顺序。

关于angular - ngrx更新数组内的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61564617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com