Reputation: 403
I am new to Immutable and I am pretty confused that how to delete an array element which is inside a Map. I don't want to use fromJs
. I know there is a lot of resources on Stack Overflow but the don't work for me.
const test = Map({
arr: [{
id: 1
}, {
id: 2
}, {
id: 3
}]
});
console.log(test.get('arr'))
Before
arr:[{id:1},{id:2},{id:3}]
I want to remove id : 3
arr:[{id:1},{id:2}]
Upvotes: 0
Views: 1503
Reputation: 913
The basic problem here is that when you create a Map it only shallowly converts the object keys in to Map keys. It does not deeply convert the object. This is ok, but you have to handle this case correctly and it can be a bit confusing when you're first dealing with this situation.
First, you should understand that this...
const test = Map({
arr: [{
id: 1
}, {
id: 2
}, {
id: 3
}]
})
Is this...
Map {
arr: [
{ id: 1 },
{ id: 2 },
{ id: 3 }
]
}
Where the value stored at arr
is an Array and not an immutable List and the values stored in that array are objects not Maps.
To change the mutable values you will need to update the Map and change the array at the same time. Note that you want to do this immutably so that you do not change the mutable values stored in your immutable Map. The immutable way of doing this would look something like the following.
If you know the index of where the object with id: 3
is located, then you can slice out that index...
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))
})
If you don't know the index then you can filter the array...
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)
})
This experience can be a bit painful so I wrote mudash to specifically help when dealing with mixed nested data structures. You can achieve the same as above doing this with 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))
Upvotes: 2
Reputation: 5387
When using Immutable.js, you are generally not supposed to use Plain JS data structures. So you can create your data like:
test = Map({ arr: List([ Map({ id: 1 }), Map({ id: 2 }), Map({ id: 3 }) ]) })
and can remove the third object as follows:
test.set('arr', test.get('arr').filter(x => x.get('id') != 3))
Upvotes: 1