How to loop through an Immutable Map of Immutable Maps?
Asked Answered
P

2

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.

Procephalic answered 7/11, 2016 at 22:7 Comment(1)
Provide an example of the desired outcome. Do you know how to iterate over the keys of the Map with the 1 level depth?Cowpox
A
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]}`));
Amaleta answered 7/11, 2016 at 22:15 Comment(2)
Thanks, it helps me a lot. By thePaapanen
Gold. It's a pity that ImmutableJS descriptions are TypeScript oriented and thus hard to comprehend for a lot of folks.Personate
C
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)

}
Cysticercus answered 15/1, 2019 at 10:45 Comment(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!Eliathas

© 2022 - 2024 — McMap. All rights reserved.