【问题标题】:How to iterate over array of objects and change property in redux?如何迭代对象数组并更改redux中的属性?
【发布时间】:2019-04-18 15:01:04
【问题描述】:

我的状态中有这个数组:

state:{     
   items:[{id:0},{id:1},{id:2},{id:3}]
}

我可以做到: 我可以删除其中一个对象,例如,第二个,数组会是这样的:

 items:[{id:0},{id:2},{id:3}]

我想做什么(我需要帮助)

我想遍历数组并将 id 设置为数组中它自己的索引位置,变成这样:

 items:[{id:0},{id:1},{id:2}]

因此,具有 Id:2 和 Id:3 的对象将根据其新的索引位置分别设置为 Id:1 和 Id:2。

我怎样才能实现它?

我在reducer中使用下面的代码来删除想要的对象:

if(action.type==='deleteItem'){
    return{
        ...state,
        items:[
            ...state.items.slice(0,action.index),
            ...state.items.slice(action.index+1),
        ]

    }
}

如何实现它以根据数组的新索引位置更改数组每个对象中的 Id 属性?

感谢大家的关注!

【问题讨论】:

    标签: javascript arrays redux


    【解决方案1】:

    您可以在删除一项后映射结果数组,如下所示:

    return {
        ...state,
        items: [
            ...state.items.slice(0,action.index),
            ...state.items.slice(action.index + 1),
        ].map((item, index) => ({ ...item, id: index }))
    }
    

    【讨论】:

    • 谢谢你,它工作得很好!但是,您的答案中有一个错误类型,不需要 map 参数之后的第二个括号。 (:
    • @RogerPeixoto 你说得对,我在没有实际运行代码的情况下输入了这个哈哈。我会编辑它,以防将来有人偶然发现这个答案。很高兴它起作用了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    相关资源
    最近更新 更多