16

I've got an immutable map of maps.

let mapOfMaps = Immutable.fromJS({
    'abc': {
         id: 1
         type: 'request'
    },
    'def': {
        id: 2
        type: 'response'
    },
    'ghi': {
        type: cancel'
    },
    'jkl': {
        type: 'edit'
    }
});

How can I

  1. loop through mapOfMaps and get all the keys to print them out?
  2. loop through the keys of mapOfMaps to get all of the contents of the key?

I don't have the option of switching to a List at this stage.

I don't know how to loop through the keys.

user1261710
  • 2,539
  • 5
  • 41
  • 72
  • Provide an example of the desired outcome. Do you know how to iterate over the keys of the `Map` with the 1 level depth? – zerkms Nov 07 '16 at 22:09

2 Answers2

47

With keySeq()/valueSeq() method you get sequence of keys/values. Then you can iterate it for example with forEach():

let mapOfMaps = Immutable.fromJS({
    abc: {
         id: 1,
         type: 'request'
    },
    def: {
        id: 2,
        type: 'response'
    },
    ghi: {
        type: 'cancel'
    },
    jkl: {
        type: 'edit'
    }
});

// iterate keys
mapOfMaps.keySeq().forEach(k => console.log(k));

// iterate values
mapOfMaps.valueSeq().forEach(v => console.log(v));

Furthermore you can iterate both in one loop with entrySeq():

mapOfMaps.entrySeq().forEach(e => console.log(`key: ${e[0]}, value: ${e[1]}`));
madox2
  • 49,493
  • 17
  • 99
  • 99
4

If we need key:value together, we can use forloop also. forloop provides flexibility to put a break; for a desired condition match.

//Iterating over key:value pair in Immutable JS map object.

for(let [key, value] of mapOfMaps) {
       console.log(key, value)

}
sat20786
  • 1,466
  • 1
  • 10
  • 11
  • 1
    I appreciate this answer as my goal was to iterate and then update the value based on a condition. So this allows me to add my updating function within the for loop, thanks buddy! – Emma Earl Kent Sep 15 '22 at 22:35