Fossmo
Fossmo

Reputation: 2892

How to update list in list in ImmutableJS?

I have problems updating a list inside a list in ImmutableJS. Can anyone tell me what I'm doing wrong?

var rows = Immutable.List();
for (var i = 0; i < 12; i++) {
  rows = rows.push({type:"floor"});
}

var cols = Immutable.List();
for (var j = 0; j < 12; j++) {
  cols = cols.push(rows);
}

var wall = {type:"wall"};

cols = cols.update(cols.get(3).get(4), function(wall) { return wall});

// I expect to get 'wall' written in the console, but the output is 'floor'.
console.log(cols.get(3).get(4).type);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.6/immutable.js"></script>

Upvotes: 0

Views: 130

Answers (1)

alexander.polomodov
alexander.polomodov

Reputation: 5534

You can separate updating into two steps (see example on jsfiddle):

var rows = Immutable.List();
for (var i = 0; i < 12; i++) {
  rows = rows.push({type:"floor"});
}

var cols = Immutable.List();
for (var j = 0; j < 12; j++) {
  cols = cols.push(rows);
}

var wall = {type:"wall"};
var nestedList = cols.get(3);
var newNestedList;
var newCols;
newNestedList = nestedList.update(4, function(item) {return wall});
newCols = cols.update(3, function(list) { return newNestedList});
console.log(newCols.get(3).get(4).type);

Upvotes: 1

Related Questions