如何使用 ImmutableJS 更新 fromJS 中的对象?

How to update object inside fromJS with ImmutableJS?

您好,我是 ImmutableJs 的新手。我想更新 ImmutableJs 数组中的特定对象。

这是我的数组

const todos = Immutable.fromJS([{
               text: 'ADDED TODO',
               id: 0,
               todo:[]
            },
            {
               text: 'DELETED TODO',
               id: 1,
               todo:[]
             },
             {
               text: 'DELETED TODO',
               id: 1,
               todo:[]
             }]);

现在我想将第二个对象中id为1的对象压入todo空数组中。

谁能推荐一下方法??

如果您的列表按 id 排序,您可以这样做:

const newTodos = todos.update(
    1,
    map => map.update(
        "todo",
        list => list.push("item")
    )
);

首先update找到具有相应索引的Map并将其应用于函数。第二个 update 类似,它找到带有 todo 的键并将其应用到另一个函数。然后,您只需将任何项目推入 todo 列表即可。

如果您不确定id是否对应索引,请将1替换为findIndex如下。

todos.findIndex(todo => todo.get("id") === 1),