gpt4 book ai didi

javascript - 如何在 Immutable js 中删除 Map 中的数组元素?

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

我是 Immutable 的新手,我对如何删除 Map 内的数组元素感到非常困惑。我不想使用 fromJs。我知道 Stack Overflow 上有很多资源,但对我来说不起作用。

const test = Map({
arr: [{
id: 1
}, {
id: 2
}, {
id: 3
}]
});


console.log(test.get('arr'))

之前

arr:[{id:1},{id:2},{id:3}]

我想删除 id : 3

arr:[{id:1},{id:2}]

最佳答案

这里的基本问题是,当您创建 Map 时,它仅将对象键浅层转换为 Map 键。它不会深度转换对象。这没问题,但是您必须正确处理这种情况,并且当您第一次处理这种情况时可能会有点困惑。

首先,你应该明白这......

const test = Map({
arr: [{
id: 1
}, {
id: 2
}, {
id: 3
}]
})

这是……

Map {
arr: [
{ id: 1 },
{ id: 2 },
{ id: 3 }
]
}

存储在arr中的值是一个数组而不是一个不可变的列表,并且存储在该数组中的值是对象而不是映射。

要更改可变值,您需要更新映射并同时更改数组。请注意,您希望以不可变的方式执行此操作,以便您不会更改存储在不可变映射中的可变值。执行此操作的不可变方法如下所示。

如果您知道 id: 3 的对象所在的索引,那么您可以切出该索引...

const i = 2
test = test // remember that any change to an immutable object creates a new object, so assignment is required
.update('arr', (arr) => {
return arr.slice(0, i).concat(arr.slice(i + 1))
})

如果您不知道索引,则可以过滤数组...

test = test  // remember that any change to an immutable object creates a new object, so assignment is required
.update('arr', (arr) => {
return arr.filter((obj) => obj.id !== 3)
})

这种经历可能有点痛苦,所以我写了mudash在处理混合嵌套数据结构时特别有帮助。您可以使用 mudash 实现与上面相同的效果...

const _ = require('mudash')

// delete, this correctly traverses mixed structures...
test = _.delete(test, 'arr.2')

//update/filter, these methods correctly handle both immutable and stadard js types...
test = _.update(test, 'arr', (arr) => _.filter(arr, (obj) => obj.id !== 3))

关于javascript - 如何在 Immutable js 中删除 Map 中的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44848700/

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