You can reduce the input list into new Immutable.Map:
var ys = xs.reduce(
function(result, item) { return result.set(item.get('key'), item); },
Immutable.Map());
There is no intermediate representation in this case, but the immutable map has to be updated (in fact, new instance must be created) in every iteration and that that can be suboptimal (depending on the actual implementation of Immutable.Map).
You can optimize it reducing into regular javascript object and convert it to immutable map at the end:
var ys = Immutable.Map(xs.reduce(
function(result, item) { result[item.get('key')] = item; return result; },
{}));
But that is certainly less idiomatic.
You'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.
Best Solution
You are looking for the
splice
method:Where you can specify the
index
and if you write0
asremoveNum
it will just insert the values at the given position:Demo JSFiddle.