I'm just starting with immutable.js and I'm having trouble figuring out how to set a new property on objects within an array. I'm having trouble finding any examples in the docs of this kind of change.
I'm basically just trying to take change this:
[{
gitInfo: {id: 8001, host: '', …},
module: {id: 24875, name: "blah", …}
}...]
to this:
[{
gitInfo: {id: 8001, host: '', …},
module: {id: 24875, name: "blah", isStared: true …}
}...]
So w/out immutable.js I would have something like:
function markModules(modules) {
modules.map( (module) => {
module.module.isStarred = false;
if (contains(this.props.stars, module.module.id)) {
module.module.isStarred = true;
}
})
return modules;
}
I'm assuming I need something like set() with a List, but again, I'm not finding any examples how to do this.
Thanks for any tips or links to examples.
I'm just starting with immutable.js and I'm having trouble figuring out how to set a new property on objects within an array. I'm having trouble finding any examples in the docs of this kind of change.
I'm basically just trying to take change this:
[{
gitInfo: {id: 8001, host: '', …},
module: {id: 24875, name: "blah", …}
}...]
to this:
[{
gitInfo: {id: 8001, host: '', …},
module: {id: 24875, name: "blah", isStared: true …}
}...]
So w/out immutable.js I would have something like:
function markModules(modules) {
modules.map( (module) => {
module.module.isStarred = false;
if (contains(this.props.stars, module.module.id)) {
module.module.isStarred = true;
}
})
return modules;
}
I'm assuming I need something like set() with a List, but again, I'm not finding any examples how to do this.
Thanks for any tips or links to examples.
Share Improve this question edited Sep 5, 2015 at 1:16 Ben asked Sep 5, 2015 at 1:09 BenBen 5,3619 gold badges39 silver badges45 bronze badges1 Answer
Reset to default 6You'd do it the same way you would without Immutable.js (.map
).
const data = Immutable.fromJS([{
gitInfo: {id: 8001, host: ''},
module: {id: 24875, name: "blah"}
}, {
gitInfo: {id: 6996, host: ''},
module: {id: 666, name: "wef"}
}]);
const transformed = data.map((x) => {
return x.get('module').set('isStarred', true);
})
transformed.toJS() === [
{
"id": 24875,
"name": "blah",
"isStarred": true
},
{
"id": 666,
"name": "wef",
"isStarred": true
}
]
And if you want to put the extra logic in there:
function markModules(modules) {
return modules.map((module) => {
const isStarred = contains(this.props.stars, module.getIn(['module', 'id']));
return module.setIn(['module', 'isStarred'], isStarred);
})
}
The key is to turn your if statements into values/functions that return values instead of updating the data structure.