Reputation: 2057
I have started working on Immutable.js recently and the lack of helpful examples is quite frustrating.
I have a deeply nested Immutable map whose structure looks like this. And I need to use immutable.js to update page data of chapter with id '264'.
var publisherData = {
"id": 367,
"publisher": {
"author": {
"id": 13,
"books": [
{
"id": 13,
"sections": [
{
"id": 49,
"chapters": [
{
"id": 262,
"pages": null
},
{
"id": 263,
"pages": null
},
{
"id": 264,
"pages":null
},
{
"id": 265,
"pages": {
"id": 159
},
}
]
},
{
"id": 50,
"chapters": [
{
"id": 266,
"pages": null
},
{
"id": 267,
"pages": null
},
{
"id": 268,
"pages": null
},
{
"id": 269,
"pages": null
},
{
"id": 270,
"pages": null
},
{
"id": 271,
"pages": null
},
{
"id": 272,
"pages": null
}
]
},
{
"id": 51,
"chapters": [
{
"id": 273,
"pages": null
}
]
},
{
"id": 52,
"chapters": [
{
"id": 277,
"pages": null
}
]
}
]
}
]
}
}
I managed to get the relevant moduleIndex and sectionIndex using this code -
immutableStub.getIn(["publisher","author", "books"]).map((module,i) => {
return module.get('sections').map((section,j) => {
return section.get('chapters').map((chapter,k) => {
if(chapter.get('id') == '273'){
moduleIndex = i;
sectionIndex = j;
chapterIndex = k;
}
})
})
})
How can I proceed from here? I cannot use 'updateIn' because the keyPath only stretches partially - "publisher","author", "books" - and then it's a list.
Please suggest a solution.
Upvotes: 0
Views: 100
Reputation: 10837
You are almost there...
immutableStub.getIn([ "publisher", "author", "books" ]).map(( module, i ) => {
return module.get('sections').map(( section, j ) => {
return section.get('chapters').map(( chapter, k ) => {
if ( chapter.get('id') == '273' ) {
moduleIndex = i;
sectionIndex = j;
chapterIndex = k;
chapterToUpdate = chapter;
}
})
})
})
if ( chapterToUpdate ) {
// ...make changes to chapterToUpdate...
immutableStub = immutableStub.setIn([
"publisher",
"author",
"books",
moduleIndex,
"sections",
sectionIndex,
"chapters",
chapterIndex
], chapterToUpdate);
}
Upvotes: 1