user1261710 user1261710 - 1 month ago 39
Javascript Question

How to loop through an Immutable Map of Immutable Maps?

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.

Answer

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]}`));