Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 601
user1261710 Avatar asked Nov 07 '16 22:11

user1261710


2 Answers

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]}`));
like image 51
madox2 Avatar answered Nov 20 '22 10:11

madox2


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)

}
like image 25
sat20786 Avatar answered Nov 20 '22 11:11

sat20786